blob: efcba6df923cd2ce96a6f8c5f9952f5d2f19adc7 [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
Skip Montanaro4d5d5bf2000-07-13 01:01:03 +000010
Guido van Rossum555915a1994-02-24 11:32:59 +000011
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
Guido van Rossum555915a1994-02-24 11:32:59 +000016def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000017 """Normalize case of pathname.
18
Guido van Rossum534972b1999-02-03 17:20:50 +000019 Makes all characters lowercase and all slashes into backslashes."""
Fred Drakeb4e460a2000-09-28 16:25:20 +000020 return s.replace("/", "\\").lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000021
Guido van Rossum77e1db31997-06-02 23:11:57 +000022
Fred Drakeef0b5dd2000-02-17 17:30:40 +000023# Return whether a path is absolute.
Guido van Rossum555915a1994-02-24 11:32:59 +000024# Trivial in Posix, harder on the Mac or MS-DOS.
25# For DOS it is absolute if it starts with a slash or backslash (current
Guido van Rossum534972b1999-02-03 17:20:50 +000026# volume), or if a pathname after the volume letter and colon / UNC resource
27# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000028
29def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000030 """Test whether a path is absolute"""
31 s = splitdrive(s)[1]
32 return s != '' and s[:1] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +000033
34
Guido van Rossum77e1db31997-06-02 23:11:57 +000035# Join two (or more) paths.
36
Barry Warsaw384d2491997-02-18 21:53:25 +000037def join(a, *p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000038 """Join two or more pathname components, inserting "\\" as needed"""
39 path = a
40 for b in p:
41 if isabs(b):
42 path = b
Tim Peters0eeba5b2000-09-19 20:39:32 +000043 elif path == '' or path[-1:] in '/\\:':
Guido van Rossum15e22e11997-12-05 19:03:01 +000044 path = path + b
45 else:
Fred Drakeb4e460a2000-09-28 16:25:20 +000046 path = path + "\\" + b
Guido van Rossum15e22e11997-12-05 19:03:01 +000047 return path
Guido van Rossum555915a1994-02-24 11:32:59 +000048
49
50# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +000051# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +000052# It is always true that drivespec + pathspec == p
53def splitdrive(p):
Guido van Rossumf3c695c1999-04-06 19:32:19 +000054 """Split a pathname into drive and path specifiers. Returns a 2-tuple
55"(drive,path)"; either part may be empty"""
Guido van Rossum15e22e11997-12-05 19:03:01 +000056 if p[1:2] == ':':
57 return p[0:2], p[2:]
Guido van Rossumf3c695c1999-04-06 19:32:19 +000058 return '', p
59
60
61# Parse UNC paths
62def splitunc(p):
63 """Split a pathname into UNC mount point and relative path specifiers.
64
65 Return a 2-tuple (unc, rest); either part may be empty.
66 If unc is not empty, it has the form '//host/mount' (or similar
67 using backslashes). unc+rest is always the input path.
68 Paths containing drive letters never have an UNC part.
69 """
70 if p[1:2] == ':':
71 return '', p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +000072 firstTwo = p[0:2]
73 if firstTwo == '//' or firstTwo == '\\\\':
74 # is a UNC path:
75 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
76 # \\machine\mountpoint\directories...
77 # directory ^^^^^^^^^^^^^^^
78 normp = normcase(p)
Fred Drakeb4e460a2000-09-28 16:25:20 +000079 index = normp.find('\\', 2)
Guido van Rossum534972b1999-02-03 17:20:50 +000080 if index == -1:
81 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
82 return ("", p)
Fred Drakeb4e460a2000-09-28 16:25:20 +000083 index = normp.find('\\', index + 1)
Guido van Rossum534972b1999-02-03 17:20:50 +000084 if index == -1:
85 index = len(p)
86 return p[:index], p[index:]
Guido van Rossum15e22e11997-12-05 19:03:01 +000087 return '', p
Guido van Rossum555915a1994-02-24 11:32:59 +000088
89
90# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +000091# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +000092# join(head, tail) == p holds.
93# The resulting head won't end in '/' unless it is the root.
94
95def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +000096 """Split a pathname.
97
98 Return tuple (head, tail) where tail is everything after the final slash.
99 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000100
Guido van Rossum15e22e11997-12-05 19:03:01 +0000101 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000102 # set i to index beyond p's last slash
103 i = len(p)
104 while i and p[i-1] not in '/\\':
105 i = i - 1
106 head, tail = p[:i], p[i:] # now tail has no slashes
107 # remove trailing slashes from head, unless it's all slashes
108 head2 = head
109 while head2 and head2[-1] in '/\\':
110 head2 = head2[:-1]
111 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000112 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000113
114
115# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000116# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000117# pathname component; the root is everything before that.
118# It is always true that root + ext == p.
119
120def splitext(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000121 """Split the extension from a pathname.
122
123 Extension is everything from the last dot to the end.
124 Return (root, ext), either part may be empty."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000125 root, ext = '', ''
126 for c in p:
127 if c in ['/','\\']:
128 root, ext = root + ext + c, ''
129 elif c == '.':
130 if ext:
131 root, ext = root + ext, c
132 else:
133 ext = c
134 elif ext:
135 ext = ext + c
136 else:
137 root = root + c
138 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000139
140
141# Return the tail (basename) part of a path.
142
143def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000144 """Returns the final component of a pathname"""
145 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000146
147
148# Return the head (dirname) part of a path.
149
150def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000151 """Returns the directory component of a pathname"""
152 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000153
154
155# Return the longest prefix of all list elements.
156
157def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000158 "Given a list of pathnames, returns the longest common leading component"
159 if not m: return ''
Skip Montanaro62358312000-08-22 13:01:53 +0000160 prefix = m[0]
161 for item in m:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000162 for i in range(len(prefix)):
163 if prefix[:i+1] <> item[:i+1]:
164 prefix = prefix[:i]
165 if i == 0: return ''
166 break
Skip Montanaro62358312000-08-22 13:01:53 +0000167 return prefix
Guido van Rossum555915a1994-02-24 11:32:59 +0000168
169
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000170# Get size, mtime, atime of files.
171
172def getsize(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000173 """Return the size of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000174 st = os.stat(filename)
175 return st[stat.ST_SIZE]
176
177def getmtime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000178 """Return the last modification time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000179 st = os.stat(filename)
180 return st[stat.ST_MTIME]
181
182def getatime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000183 """Return the last access time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000184 st = os.stat(filename)
Fred Drake162bd852000-07-01 06:36:51 +0000185 return st[stat.ST_ATIME]
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000186
187
Guido van Rossum555915a1994-02-24 11:32:59 +0000188# Is a path a symbolic link?
189# This will always return false on systems where posix.lstat doesn't exist.
190
191def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000192 """Test for symbolic link. On WindowsNT/95 always returns false"""
193 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000194
195
196# Does a path exist?
197# This is false for dangling symbolic links.
198
199def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000200 """Test whether a path exists"""
201 try:
202 st = os.stat(path)
203 except os.error:
204 return 0
205 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000206
207
208# Is a path a dos directory?
209# This follows symbolic links, so both islink() and isdir() can be true
210# for the same path.
211
212def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000213 """Test whether a path is a directory"""
214 try:
215 st = os.stat(path)
216 except os.error:
217 return 0
218 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000219
220
221# Is a path a regular file?
222# This follows symbolic links, so both islink() and isdir() can be true
223# for the same path.
224
225def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000226 """Test whether a path is a regular file"""
227 try:
228 st = os.stat(path)
229 except os.error:
230 return 0
231 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000232
233
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000234# Is a path a mount point? Either a root (with or without drive letter)
235# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000236
237def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000238 """Test whether a path is a mount point (defined as root of drive)"""
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000239 unc, rest = splitunc(path)
240 if unc:
241 return rest in ("", "/", "\\")
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000242 p = splitdrive(path)[1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000243 return len(p) == 1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000244
245
246# Directory tree walk.
247# For each directory under top (including top itself, but excluding
248# '.' and '..'), func(arg, dirname, filenames) is called, where
249# dirname is the name of the directory and filenames is the list
250# files files (and subdirectories etc.) in the directory.
251# The func may modify the filenames list, to implement a filter,
252# or to impose a different order of visiting.
253
254def walk(top, func, arg):
Guido van Rossum534972b1999-02-03 17:20:50 +0000255 """Directory tree walk whth callback function.
256
Guido van Rossumf618a481999-11-02 13:29:08 +0000257 walk(top, func, arg) calls func(arg, d, files) for each directory d
Guido van Rossum534972b1999-02-03 17:20:50 +0000258 in the tree rooted at top (including top itself); files is a list
259 of all the files and subdirs in directory d."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000260 try:
261 names = os.listdir(top)
262 except os.error:
263 return
264 func(arg, top, names)
265 exceptions = ('.', '..')
266 for name in names:
267 if name not in exceptions:
268 name = join(top, name)
269 if isdir(name):
270 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000271
272
273# Expand paths beginning with '~' or '~user'.
274# '~' means $HOME; '~user' means that user's home directory.
275# If the path doesn't begin with '~', or if the user or $HOME is unknown,
276# the path is returned unchanged (leaving error reporting to whatever
277# function is called with the expanded path as argument).
278# See also module 'glob' for expansion of *, ? and [...] in pathnames.
279# (A function should also be defined to do full *sh-style environment
280# variable expansion.)
281
282def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000283 """Expand ~ and ~user constructs.
284
285 If user or $HOME is unknown, do nothing."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000286 if path[:1] <> '~':
287 return path
288 i, n = 1, len(path)
289 while i < n and path[i] not in '/\\':
Fred Drakeb4e460a2000-09-28 16:25:20 +0000290 i = i + 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000291 if i == 1:
292 if os.environ.has_key('HOME'):
293 userhome = os.environ['HOME']
294 elif not os.environ.has_key('HOMEPATH'):
295 return path
296 else:
297 try:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000298 drive = os.environ['HOMEDRIVE']
Guido van Rossum15e22e11997-12-05 19:03:01 +0000299 except KeyError:
300 drive = ''
301 userhome = join(drive, os.environ['HOMEPATH'])
302 else:
303 return path
304 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000305
306
307# Expand paths containing shell variable substitutions.
308# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000309# - no expansion within single quotes
310# - no escape character, except for '$$' which is translated into '$'
311# - ${varname} is accepted.
312# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000313# XXX With COMMAND.COM you can use any characters in a variable name,
314# XXX except '^|<>='.
315
Guido van Rossum15e22e11997-12-05 19:03:01 +0000316def expandvars(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000317 """Expand shell variables of form $var and ${var}.
318
319 Unknown variables are left unchanged."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000320 if '$' not in path:
321 return path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000322 import string
323 varchars = string.letters + string.digits + '_-'
Guido van Rossum15e22e11997-12-05 19:03:01 +0000324 res = ''
325 index = 0
326 pathlen = len(path)
327 while index < pathlen:
328 c = path[index]
329 if c == '\'': # no expansion within single quotes
330 path = path[index + 1:]
331 pathlen = len(path)
332 try:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000333 index = path.index('\'')
Guido van Rossum15e22e11997-12-05 19:03:01 +0000334 res = res + '\'' + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000335 except ValueError:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000336 res = res + path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000337 index = pathlen - 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000338 elif c == '$': # variable or '$$'
339 if path[index + 1:index + 2] == '$':
340 res = res + c
341 index = index + 1
342 elif path[index + 1:index + 2] == '{':
343 path = path[index+2:]
344 pathlen = len(path)
345 try:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000346 index = path.index('}')
Guido van Rossum15e22e11997-12-05 19:03:01 +0000347 var = path[:index]
348 if os.environ.has_key(var):
349 res = res + os.environ[var]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000350 except ValueError:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000351 res = res + path
352 index = pathlen - 1
353 else:
354 var = ''
355 index = index + 1
356 c = path[index:index + 1]
357 while c != '' and c in varchars:
358 var = var + c
359 index = index + 1
360 c = path[index:index + 1]
361 if os.environ.has_key(var):
362 res = res + os.environ[var]
363 if c != '':
364 res = res + c
365 else:
366 res = res + c
367 index = index + 1
368 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000369
370
371# 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 +0000372# Previously, this function also truncated pathnames to 8+3 format,
373# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000374
375def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000376 """Normalize path, eliminating double slashes, etc."""
Fred Drakeb4e460a2000-09-28 16:25:20 +0000377 path = path.replace("/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000378 prefix, path = splitdrive(path)
Fred Drakeb4e460a2000-09-28 16:25:20 +0000379 while path[:1] == "\\":
380 prefix = prefix + "\\"
Guido van Rossum15e22e11997-12-05 19:03:01 +0000381 path = path[1:]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000382 comps = path.split("\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000383 i = 0
384 while i < len(comps):
385 if comps[i] == '.':
386 del comps[i]
387 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
388 del comps[i-1:i+1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000389 i = i - 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000390 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
391 del comps[i]
392 else:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000393 i = i + 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000394 # If the path is now empty, substitute '.'
395 if not prefix and not comps:
396 comps.append('.')
Fred Drakeb4e460a2000-09-28 16:25:20 +0000397 return prefix + "\\".join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000398
399
400# Return an absolute path.
401def abspath(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000402 """Return the absolute version of a path"""
Guido van Rossum9787bea1999-01-29 22:30:41 +0000403 try:
404 import win32api
Guido van Rossum9787bea1999-01-29 22:30:41 +0000405 except ImportError:
Guido van Rossum823e91c2000-02-02 16:54:39 +0000406 global abspath
407 def _abspath(path):
408 if not isabs(path):
409 path = join(os.getcwd(), path)
410 return normpath(path)
411 abspath = _abspath
412 return _abspath(path)
Mark Hammond647d2fe2000-08-14 06:20:32 +0000413 if path: # Empty path must return current working directory.
414 try:
415 path = win32api.GetFullPathName(path)
416 except win32api.error:
417 pass # Bad path - return unchanged.
418 else:
419 path = os.getcwd()
Guido van Rossum6dfc7921999-11-30 15:00:00 +0000420 return normpath(path)