blob: a1fcaa90de4ec32b830e78c8a3af3127596f23ee [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.
Guido van Rossum534972b1999-02-03 17:20:50 +00003
4Instead of importing this module directly, import os and refer to this
5module as os.path.
Guido van Rossum15e22e11997-12-05 19:03:01 +00006"""
Guido van Rossum555915a1994-02-24 11:32:59 +00007
8import os
9import stat
10import string
Skip Montanaro97bc98a2000-07-12 16:55:57 +000011import copy
Guido van Rossum555915a1994-02-24 11:32:59 +000012
Guido van Rossume2ad88c1997-08-12 14:46:58 +000013# Normalize the case of a pathname and map slashes to backslashes.
14# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000015# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000016
Guido van Rossum555915a1994-02-24 11:32:59 +000017def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000018 """Normalize case of pathname.
19
Guido van Rossum534972b1999-02-03 17:20:50 +000020 Makes all characters lowercase and all slashes into backslashes."""
Guido van Rossum16a0bc21998-02-18 13:48:31 +000021 return string.lower(string.replace(s, "/", "\\"))
Guido van Rossum555915a1994-02-24 11:32:59 +000022
Guido van Rossum77e1db31997-06-02 23:11:57 +000023
Fred Drakeef0b5dd2000-02-17 17:30:40 +000024# Return whether a path is absolute.
Guido van Rossum555915a1994-02-24 11:32:59 +000025# Trivial in Posix, harder on the Mac or MS-DOS.
26# For DOS it is absolute if it starts with a slash or backslash (current
Guido van Rossum534972b1999-02-03 17:20:50 +000027# volume), or if a pathname after the volume letter and colon / UNC resource
28# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000029
30def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000031 """Test whether a path is absolute"""
32 s = splitdrive(s)[1]
33 return s != '' and s[:1] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +000034
35
Guido van Rossum77e1db31997-06-02 23:11:57 +000036# Join two (or more) paths.
37
Barry Warsaw384d2491997-02-18 21:53:25 +000038def join(a, *p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000039 """Join two or more pathname components, inserting "\\" as needed"""
40 path = a
41 for b in p:
42 if isabs(b):
43 path = b
44 elif path == '' or path[-1:] in '/\\':
45 path = path + b
46 else:
47 path = path + os.sep + b
48 return path
Guido van Rossum555915a1994-02-24 11:32:59 +000049
50
51# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +000052# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +000053# It is always true that drivespec + pathspec == p
54def splitdrive(p):
Guido van Rossumf3c695c1999-04-06 19:32:19 +000055 """Split a pathname into drive and path specifiers. Returns a 2-tuple
56"(drive,path)"; either part may be empty"""
Guido van Rossum15e22e11997-12-05 19:03:01 +000057 if p[1:2] == ':':
58 return p[0:2], p[2:]
Guido van Rossumf3c695c1999-04-06 19:32:19 +000059 return '', p
60
61
62# Parse UNC paths
63def splitunc(p):
64 """Split a pathname into UNC mount point and relative path specifiers.
65
66 Return a 2-tuple (unc, rest); either part may be empty.
67 If unc is not empty, it has the form '//host/mount' (or similar
68 using backslashes). unc+rest is always the input path.
69 Paths containing drive letters never have an UNC part.
70 """
71 if p[1:2] == ':':
72 return '', p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +000073 firstTwo = p[0:2]
74 if firstTwo == '//' or firstTwo == '\\\\':
75 # is a UNC path:
76 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
77 # \\machine\mountpoint\directories...
78 # directory ^^^^^^^^^^^^^^^
79 normp = normcase(p)
80 index = string.find(normp, '\\', 2)
81 if index == -1:
82 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
83 return ("", p)
84 index = string.find(normp, '\\', index + 1)
85 if index == -1:
86 index = len(p)
87 return p[:index], p[index:]
Guido van Rossum15e22e11997-12-05 19:03:01 +000088 return '', p
Guido van Rossum555915a1994-02-24 11:32:59 +000089
90
91# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +000092# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +000093# join(head, tail) == p holds.
94# The resulting head won't end in '/' unless it is the root.
95
96def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +000097 """Split a pathname.
98
99 Return tuple (head, tail) where tail is everything after the final slash.
100 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000101
Guido van Rossum15e22e11997-12-05 19:03:01 +0000102 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000103 # set i to index beyond p's last slash
104 i = len(p)
105 while i and p[i-1] not in '/\\':
106 i = i - 1
107 head, tail = p[:i], p[i:] # now tail has no slashes
108 # remove trailing slashes from head, unless it's all slashes
109 head2 = head
110 while head2 and head2[-1] in '/\\':
111 head2 = head2[:-1]
112 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000113 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000114
115
116# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000117# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000118# pathname component; the root is everything before that.
119# It is always true that root + ext == p.
120
121def splitext(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000122 """Split the extension from a pathname.
123
124 Extension is everything from the last dot to the end.
125 Return (root, ext), either part may be empty."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000126 root, ext = '', ''
127 for c in p:
128 if c in ['/','\\']:
129 root, ext = root + ext + c, ''
130 elif c == '.':
131 if ext:
132 root, ext = root + ext, c
133 else:
134 ext = c
135 elif ext:
136 ext = ext + c
137 else:
138 root = root + c
139 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000140
141
142# Return the tail (basename) part of a path.
143
144def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000145 """Returns the final component of a pathname"""
146 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000147
148
149# Return the head (dirname) part of a path.
150
151def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000152 """Returns the directory component of a pathname"""
153 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000154
155
156# Return the longest prefix of all list elements.
157
158def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000159 "Given a list of pathnames, returns the longest common leading component"
160 if not m: return ''
Skip Montanaro97bc98a2000-07-12 16:55:57 +0000161 n = copy.copy(m)
162 for i in range(len(n)):
163 n[i] = n[i].split(os.sep)
164 prefix = n[0]
165 for item in n:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000166 for i in range(len(prefix)):
167 if prefix[:i+1] <> item[:i+1]:
168 prefix = prefix[:i]
169 if i == 0: return ''
170 break
Skip Montanaro97bc98a2000-07-12 16:55:57 +0000171 return os.sep.join(prefix)
Guido van Rossum555915a1994-02-24 11:32:59 +0000172
173
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000174# Get size, mtime, atime of files.
175
176def getsize(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000177 """Return the size of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000178 st = os.stat(filename)
179 return st[stat.ST_SIZE]
180
181def getmtime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000182 """Return the last modification time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000183 st = os.stat(filename)
184 return st[stat.ST_MTIME]
185
186def getatime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000187 """Return the last access time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000188 st = os.stat(filename)
Fred Drake162bd852000-07-01 06:36:51 +0000189 return st[stat.ST_ATIME]
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000190
191
Guido van Rossum555915a1994-02-24 11:32:59 +0000192# Is a path a symbolic link?
193# This will always return false on systems where posix.lstat doesn't exist.
194
195def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000196 """Test for symbolic link. On WindowsNT/95 always returns false"""
197 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000198
199
200# Does a path exist?
201# This is false for dangling symbolic links.
202
203def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000204 """Test whether a path exists"""
205 try:
206 st = os.stat(path)
207 except os.error:
208 return 0
209 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000210
211
212# Is a path a dos directory?
213# This follows symbolic links, so both islink() and isdir() can be true
214# for the same path.
215
216def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000217 """Test whether a path is a directory"""
218 try:
219 st = os.stat(path)
220 except os.error:
221 return 0
222 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000223
224
225# Is a path a regular file?
226# This follows symbolic links, so both islink() and isdir() can be true
227# for the same path.
228
229def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000230 """Test whether a path is a regular file"""
231 try:
232 st = os.stat(path)
233 except os.error:
234 return 0
235 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000236
237
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000238# Is a path a mount point? Either a root (with or without drive letter)
239# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000240
241def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000242 """Test whether a path is a mount point (defined as root of drive)"""
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000243 unc, rest = splitunc(path)
244 if unc:
245 return rest in ("", "/", "\\")
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000246 p = splitdrive(path)[1]
247 return len(p)==1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000248
249
250# Directory tree walk.
251# For each directory under top (including top itself, but excluding
252# '.' and '..'), func(arg, dirname, filenames) is called, where
253# dirname is the name of the directory and filenames is the list
254# files files (and subdirectories etc.) in the directory.
255# The func may modify the filenames list, to implement a filter,
256# or to impose a different order of visiting.
257
258def walk(top, func, arg):
Guido van Rossum534972b1999-02-03 17:20:50 +0000259 """Directory tree walk whth callback function.
260
Guido van Rossumf618a481999-11-02 13:29:08 +0000261 walk(top, func, arg) calls func(arg, d, files) for each directory d
Guido van Rossum534972b1999-02-03 17:20:50 +0000262 in the tree rooted at top (including top itself); files is a list
263 of all the files and subdirs in directory d."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000264 try:
265 names = os.listdir(top)
266 except os.error:
267 return
268 func(arg, top, names)
269 exceptions = ('.', '..')
270 for name in names:
271 if name not in exceptions:
272 name = join(top, name)
273 if isdir(name):
274 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000275
276
277# Expand paths beginning with '~' or '~user'.
278# '~' means $HOME; '~user' means that user's home directory.
279# If the path doesn't begin with '~', or if the user or $HOME is unknown,
280# the path is returned unchanged (leaving error reporting to whatever
281# function is called with the expanded path as argument).
282# See also module 'glob' for expansion of *, ? and [...] in pathnames.
283# (A function should also be defined to do full *sh-style environment
284# variable expansion.)
285
286def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000287 """Expand ~ and ~user constructs.
288
289 If user or $HOME is unknown, do nothing."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000290 if path[:1] <> '~':
291 return path
292 i, n = 1, len(path)
293 while i < n and path[i] not in '/\\':
294 i = i+1
295 if i == 1:
296 if os.environ.has_key('HOME'):
297 userhome = os.environ['HOME']
298 elif not os.environ.has_key('HOMEPATH'):
299 return path
300 else:
301 try:
302 drive=os.environ['HOMEDRIVE']
303 except KeyError:
304 drive = ''
305 userhome = join(drive, os.environ['HOMEPATH'])
306 else:
307 return path
308 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000309
310
311# Expand paths containing shell variable substitutions.
312# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000313# - no expansion within single quotes
314# - no escape character, except for '$$' which is translated into '$'
315# - ${varname} is accepted.
316# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000317# XXX With COMMAND.COM you can use any characters in a variable name,
318# XXX except '^|<>='.
319
320varchars = string.letters + string.digits + '_-'
321
Guido van Rossum15e22e11997-12-05 19:03:01 +0000322def expandvars(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000323 """Expand shell variables of form $var and ${var}.
324
325 Unknown variables are left unchanged."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000326 if '$' not in path:
327 return path
328 res = ''
329 index = 0
330 pathlen = len(path)
331 while index < pathlen:
332 c = path[index]
333 if c == '\'': # no expansion within single quotes
334 path = path[index + 1:]
335 pathlen = len(path)
336 try:
337 index = string.index(path, '\'')
338 res = res + '\'' + path[:index + 1]
339 except string.index_error:
340 res = res + path
341 index = pathlen -1
342 elif c == '$': # variable or '$$'
343 if path[index + 1:index + 2] == '$':
344 res = res + c
345 index = index + 1
346 elif path[index + 1:index + 2] == '{':
347 path = path[index+2:]
348 pathlen = len(path)
349 try:
350 index = string.index(path, '}')
351 var = path[:index]
352 if os.environ.has_key(var):
353 res = res + os.environ[var]
354 except string.index_error:
355 res = res + path
356 index = pathlen - 1
357 else:
358 var = ''
359 index = index + 1
360 c = path[index:index + 1]
361 while c != '' and c in varchars:
362 var = var + c
363 index = index + 1
364 c = path[index:index + 1]
365 if os.environ.has_key(var):
366 res = res + os.environ[var]
367 if c != '':
368 res = res + c
369 else:
370 res = res + c
371 index = index + 1
372 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000373
374
375# 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 +0000376# Previously, this function also truncated pathnames to 8+3 format,
377# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000378
379def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000380 """Normalize path, eliminating double slashes, etc."""
Guido van Rossum16a0bc21998-02-18 13:48:31 +0000381 path = string.replace(path, "/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000382 prefix, path = splitdrive(path)
383 while path[:1] == os.sep:
384 prefix = prefix + os.sep
385 path = path[1:]
386 comps = string.splitfields(path, os.sep)
387 i = 0
388 while i < len(comps):
389 if comps[i] == '.':
390 del comps[i]
391 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
392 del comps[i-1:i+1]
393 i = i-1
394 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
395 del comps[i]
396 else:
397 i = i+1
398 # If the path is now empty, substitute '.'
399 if not prefix and not comps:
400 comps.append('.')
401 return prefix + string.joinfields(comps, os.sep)
Guido van Rossume294cf61999-01-29 18:05:18 +0000402
403
404# Return an absolute path.
405def abspath(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000406 """Return the absolute version of a path"""
Guido van Rossum9787bea1999-01-29 22:30:41 +0000407 try:
408 import win32api
Guido van Rossum9787bea1999-01-29 22:30:41 +0000409 except ImportError:
Guido van Rossum823e91c2000-02-02 16:54:39 +0000410 global abspath
411 def _abspath(path):
412 if not isabs(path):
413 path = join(os.getcwd(), path)
414 return normpath(path)
415 abspath = _abspath
416 return _abspath(path)
417 try:
418 path = win32api.GetFullPathName(path)
419 except win32api.error:
420 pass # Bad path - return unchanged.
Guido van Rossum6dfc7921999-11-30 15:00:00 +0000421 return normpath(path)