blob: 0d7ef659165109704c9b10540ee74f1115a3df35 [file] [log] [blame]
Guido van Rossum15e22e11997-12-05 19:03:01 +00001# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
2"""Common pathname manipulations, WindowsNT/95 version.
3Instead of importing this module
4directly, import os and refer to this module as os.path.
5"""
Guido van Rossum555915a1994-02-24 11:32:59 +00006
7import os
8import stat
9import string
10
11
Guido van Rossume2ad88c1997-08-12 14:46:58 +000012# Normalize the case of a pathname and map slashes to backslashes.
13# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000014# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000015
16_normtable = string.maketrans(string.uppercase + "\\/",
Guido van Rossum15e22e11997-12-05 19:03:01 +000017 string.lowercase + os.sep * 2)
Guido van Rossum555915a1994-02-24 11:32:59 +000018
19def normcase(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000020 """Normalize case of pathname. Makes all characters lowercase and all
21slashes into backslashes"""
Guido van Rossume2ad88c1997-08-12 14:46:58 +000022 return string.translate(s, _normtable)
Guido van Rossum555915a1994-02-24 11:32:59 +000023
Guido van Rossum77e1db31997-06-02 23:11:57 +000024
Guido van Rossum555915a1994-02-24 11:32:59 +000025# Return wheter a path is absolute.
26# Trivial in Posix, harder on the Mac or MS-DOS.
27# For DOS it is absolute if it starts with a slash or backslash (current
28# volume), or if a pathname after the volume letter and colon starts with
29# a slash or backslash.
30
31def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000032 """Test whether a path is absolute"""
33 s = splitdrive(s)[1]
34 return s != '' and s[:1] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +000035
36
Guido van Rossum77e1db31997-06-02 23:11:57 +000037# Join two (or more) paths.
38
Barry Warsaw384d2491997-02-18 21:53:25 +000039def join(a, *p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000040 """Join two or more pathname components, inserting "\\" as needed"""
41 path = a
42 for b in p:
43 if isabs(b):
44 path = b
45 elif path == '' or path[-1:] in '/\\':
46 path = path + b
47 else:
48 path = path + os.sep + b
49 return path
Guido van Rossum555915a1994-02-24 11:32:59 +000050
51
52# Split a path in a drive specification (a drive letter followed by a
53# colon) and the path specification.
54# It is always true that drivespec + pathspec == p
55def splitdrive(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000056 """Split a pathname into drive and path specifiers. Returns a 2-tuple
57"(drive,path)"; either part may be empty"""
58 if p[1:2] == ':':
59 return p[0:2], p[2:]
60 return '', p
Guido van Rossum555915a1994-02-24 11:32:59 +000061
62
63# Split a path in head (everything up to the last '/') and tail (the
64# rest). If the original path ends in '/' but is not the root, this
65# '/' is stripped. After the trailing '/' is stripped, the invariant
66# join(head, tail) == p holds.
67# The resulting head won't end in '/' unless it is the root.
68
69def split(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000070 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
71everything after the final slash. Either part may be empty"""
72 d, p = splitdrive(p)
73 slashes = ''
74 while p and p[-1:] in '/\\':
75 slashes = slashes + p[-1]
76 p = p[:-1]
77 if p == '':
78 p = p + slashes
79 head, tail = '', ''
80 for c in p:
81 tail = tail + c
82 if c in '/\\':
83 head, tail = head + tail, ''
84 slashes = ''
85 while head and head[-1:] in '/\\':
86 slashes = slashes + head[-1]
87 head = head[:-1]
88 if head == '':
89 head = head + slashes
90 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +000091
92
93# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +000094# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +000095# pathname component; the root is everything before that.
96# It is always true that root + ext == p.
97
98def splitext(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000099 """Split the extension from a pathname. Extension is everything from the
100last dot to the end. Returns "(root, ext)", either part may be empty"""
101 root, ext = '', ''
102 for c in p:
103 if c in ['/','\\']:
104 root, ext = root + ext + c, ''
105 elif c == '.':
106 if ext:
107 root, ext = root + ext, c
108 else:
109 ext = c
110 elif ext:
111 ext = ext + c
112 else:
113 root = root + c
114 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000115
116
117# Return the tail (basename) part of a path.
118
119def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000120 """Returns the final component of a pathname"""
121 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000122
123
124# Return the head (dirname) part of a path.
125
126def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000127 """Returns the directory component of a pathname"""
128 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000129
130
131# Return the longest prefix of all list elements.
132
133def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000134 "Given a list of pathnames, returns the longest common leading component"
135 if not m: return ''
136 prefix = m[0]
137 for item in m:
138 for i in range(len(prefix)):
139 if prefix[:i+1] <> item[:i+1]:
140 prefix = prefix[:i]
141 if i == 0: return ''
142 break
143 return prefix
Guido van Rossum555915a1994-02-24 11:32:59 +0000144
145
146# Is a path a symbolic link?
147# This will always return false on systems where posix.lstat doesn't exist.
148
149def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000150 """Test for symbolic link. On WindowsNT/95 always returns false"""
151 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000152
153
154# Does a path exist?
155# This is false for dangling symbolic links.
156
157def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000158 """Test whether a path exists"""
159 try:
160 st = os.stat(path)
161 except os.error:
162 return 0
163 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000164
165
166# Is a path a dos directory?
167# This follows symbolic links, so both islink() and isdir() can be true
168# for the same path.
169
170def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000171 """Test whether a path is a directory"""
172 try:
173 st = os.stat(path)
174 except os.error:
175 return 0
176 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000177
178
179# Is a path a regular file?
180# This follows symbolic links, so both islink() and isdir() can be true
181# for the same path.
182
183def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000184 """Test whether a path is a regular file"""
185 try:
186 st = os.stat(path)
187 except os.error:
188 return 0
189 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000190
191
192# Are two filenames really pointing to the same file?
193
194def samefile(f1, f2):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000195 """Test whether two pathnames reference the same actual file"""
196 s1 = os.stat(f1)
197 s2 = os.stat(f2)
198 return samestat(s1, s2)
Guido van Rossum555915a1994-02-24 11:32:59 +0000199
200
201# Are two open files really referencing the same file?
202# (Not necessarily the same file descriptor!)
203# XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads?
204
205def sameopenfile(fp1, fp2):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000206 """Test whether two open file objects reference the same file (may not
207work correctly)"""
208 s1 = os.fstat(fp1.fileno())
209 s2 = os.fstat(fp2.fileno())
210 return samestat(s1, s2)
Guido van Rossum555915a1994-02-24 11:32:59 +0000211
212
213# Are two stat buffers (obtained from stat, fstat or lstat)
214# describing the same file?
215
216def samestat(s1, s2):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000217 """Test whether two stat buffers reference the same file"""
218 return s1[stat.ST_INO] == s2[stat.ST_INO] and \
219 s1[stat.ST_DEV] == s2[stat.ST_DEV]
Guido van Rossum555915a1994-02-24 11:32:59 +0000220
221
222# Is a path a mount point?
223# XXX This degenerates in: 'is this the root?' on DOS
224
225def ismount(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000226 """Test whether a path is a mount point"""
227 return isabs(splitdrive(path)[1])
Guido van Rossum555915a1994-02-24 11:32:59 +0000228
229
230# Directory tree walk.
231# For each directory under top (including top itself, but excluding
232# '.' and '..'), func(arg, dirname, filenames) is called, where
233# dirname is the name of the directory and filenames is the list
234# files files (and subdirectories etc.) in the directory.
235# The func may modify the filenames list, to implement a filter,
236# or to impose a different order of visiting.
237
238def walk(top, func, arg):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000239 """walk(top,func,args) calls func(arg, d, files) for each directory "d"
240in the tree rooted at "top" (including "top" itself). "files" is a list
241of all the files and subdirs in directory "d".
242"""
243 try:
244 names = os.listdir(top)
245 except os.error:
246 return
247 func(arg, top, names)
248 exceptions = ('.', '..')
249 for name in names:
250 if name not in exceptions:
251 name = join(top, name)
252 if isdir(name):
253 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000254
255
256# Expand paths beginning with '~' or '~user'.
257# '~' means $HOME; '~user' means that user's home directory.
258# If the path doesn't begin with '~', or if the user or $HOME is unknown,
259# the path is returned unchanged (leaving error reporting to whatever
260# function is called with the expanded path as argument).
261# See also module 'glob' for expansion of *, ? and [...] in pathnames.
262# (A function should also be defined to do full *sh-style environment
263# variable expansion.)
264
265def expanduser(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000266 """Expand ~ and ~user constructions. If user or $HOME is unknown,
267do nothing"""
268 if path[:1] <> '~':
269 return path
270 i, n = 1, len(path)
271 while i < n and path[i] not in '/\\':
272 i = i+1
273 if i == 1:
274 if os.environ.has_key('HOME'):
275 userhome = os.environ['HOME']
276 elif not os.environ.has_key('HOMEPATH'):
277 return path
278 else:
279 try:
280 drive=os.environ['HOMEDRIVE']
281 except KeyError:
282 drive = ''
283 userhome = join(drive, os.environ['HOMEPATH'])
284 else:
285 return path
286 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000287
288
289# Expand paths containing shell variable substitutions.
290# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000291# - no expansion within single quotes
292# - no escape character, except for '$$' which is translated into '$'
293# - ${varname} is accepted.
294# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000295# XXX With COMMAND.COM you can use any characters in a variable name,
296# XXX except '^|<>='.
297
298varchars = string.letters + string.digits + '_-'
299
Guido van Rossum15e22e11997-12-05 19:03:01 +0000300def expandvars(path):
301 """Expand shell variables of form $var and ${var}. Unknown variables
302are left unchanged"""
303 if '$' not in path:
304 return path
305 res = ''
306 index = 0
307 pathlen = len(path)
308 while index < pathlen:
309 c = path[index]
310 if c == '\'': # no expansion within single quotes
311 path = path[index + 1:]
312 pathlen = len(path)
313 try:
314 index = string.index(path, '\'')
315 res = res + '\'' + path[:index + 1]
316 except string.index_error:
317 res = res + path
318 index = pathlen -1
319 elif c == '$': # variable or '$$'
320 if path[index + 1:index + 2] == '$':
321 res = res + c
322 index = index + 1
323 elif path[index + 1:index + 2] == '{':
324 path = path[index+2:]
325 pathlen = len(path)
326 try:
327 index = string.index(path, '}')
328 var = path[:index]
329 if os.environ.has_key(var):
330 res = res + os.environ[var]
331 except string.index_error:
332 res = res + path
333 index = pathlen - 1
334 else:
335 var = ''
336 index = index + 1
337 c = path[index:index + 1]
338 while c != '' and c in varchars:
339 var = var + c
340 index = index + 1
341 c = path[index:index + 1]
342 if os.environ.has_key(var):
343 res = res + os.environ[var]
344 if c != '':
345 res = res + c
346 else:
347 res = res + c
348 index = index + 1
349 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000350
351
352# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
Guido van Rossum3df7b5a1996-08-26 16:35:26 +0000353# Previously, this function also truncated pathnames to 8+3 format,
354# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000355
356def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000357 """Normalize path, eliminating double slashes, etc."""
358 path = normcase(path)
359 prefix, path = splitdrive(path)
360 while path[:1] == os.sep:
361 prefix = prefix + os.sep
362 path = path[1:]
363 comps = string.splitfields(path, os.sep)
364 i = 0
365 while i < len(comps):
366 if comps[i] == '.':
367 del comps[i]
368 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
369 del comps[i-1:i+1]
370 i = i-1
371 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
372 del comps[i]
373 else:
374 i = i+1
375 # If the path is now empty, substitute '.'
376 if not prefix and not comps:
377 comps.append('.')
378 return prefix + string.joinfields(comps, os.sep)