blob: d81e8fb6450aea8d6afe0d08f557574a1487364d [file] [log] [blame]
Guido van Rossum15e22e11997-12-05 19:03:01 +00001# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
Tim Peters2344fae2001-01-15 00:50:52 +00002"""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
Skip Montanaro269b83b2001-02-06 01:07:02 +000011__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
12 "basename","dirname","commonprefix","getsize","getmtime",
13 "getatime","islink","exists","isdir","isfile","ismount",
14 "walk","expanduser","expandvars","normpath","abspath","splitunc"]
Guido van Rossum555915a1994-02-24 11:32:59 +000015
Guido van Rossume2ad88c1997-08-12 14:46:58 +000016# Normalize the case of a pathname and map slashes to backslashes.
17# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000018# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000019
Guido van Rossum555915a1994-02-24 11:32:59 +000020def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000021 """Normalize case of pathname.
22
Guido van Rossum534972b1999-02-03 17:20:50 +000023 Makes all characters lowercase and all slashes into backslashes."""
Fred Drakeb4e460a2000-09-28 16:25:20 +000024 return s.replace("/", "\\").lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000025
Guido van Rossum77e1db31997-06-02 23:11:57 +000026
Fred Drakeef0b5dd2000-02-17 17:30:40 +000027# Return whether a path is absolute.
Guido van Rossum555915a1994-02-24 11:32:59 +000028# Trivial in Posix, harder on the Mac or MS-DOS.
29# For DOS it is absolute if it starts with a slash or backslash (current
Guido van Rossum534972b1999-02-03 17:20:50 +000030# volume), or if a pathname after the volume letter and colon / UNC resource
31# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000032
33def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000034 """Test whether a path is absolute"""
35 s = splitdrive(s)[1]
36 return s != '' and s[:1] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +000037
38
Guido van Rossum77e1db31997-06-02 23:11:57 +000039# Join two (or more) paths.
40
Barry Warsaw384d2491997-02-18 21:53:25 +000041def join(a, *p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000042 """Join two or more pathname components, inserting "\\" as needed"""
43 path = a
44 for b in p:
Tim Peters1bdd0f22001-07-19 17:18:18 +000045 # If path is a raw drive letter (e.g. "C:"), and b doesn't start
46 # with a drive letter, path+b is correct, and regardless of whether
47 # b is absolute on its own.
48 if len(path) == 2 and path[-1] == ":" and splitdrive(b)[0] == "":
49 pass
50
51 # In any other case, if b is absolute it wipes out the path so far.
52 elif isabs(b) or path == "":
53 path = ""
54
55 # Else make sure a separator appears between the pieces.
56 elif path[-1:] not in "/\\":
57 b = "\\" + b
58
59 path += b
60
Guido van Rossum15e22e11997-12-05 19:03:01 +000061 return path
Guido van Rossum555915a1994-02-24 11:32:59 +000062
63
64# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +000065# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +000066# It is always true that drivespec + pathspec == p
67def splitdrive(p):
Guido van Rossumf3c695c1999-04-06 19:32:19 +000068 """Split a pathname into drive and path specifiers. Returns a 2-tuple
69"(drive,path)"; either part may be empty"""
Guido van Rossum15e22e11997-12-05 19:03:01 +000070 if p[1:2] == ':':
71 return p[0:2], p[2:]
Guido van Rossumf3c695c1999-04-06 19:32:19 +000072 return '', p
73
74
75# Parse UNC paths
76def splitunc(p):
77 """Split a pathname into UNC mount point and relative path specifiers.
78
79 Return a 2-tuple (unc, rest); either part may be empty.
80 If unc is not empty, it has the form '//host/mount' (or similar
81 using backslashes). unc+rest is always the input path.
82 Paths containing drive letters never have an UNC part.
83 """
84 if p[1:2] == ':':
85 return '', p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +000086 firstTwo = p[0:2]
87 if firstTwo == '//' or firstTwo == '\\\\':
88 # is a UNC path:
89 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
90 # \\machine\mountpoint\directories...
91 # directory ^^^^^^^^^^^^^^^
92 normp = normcase(p)
Fred Drakeb4e460a2000-09-28 16:25:20 +000093 index = normp.find('\\', 2)
Guido van Rossum534972b1999-02-03 17:20:50 +000094 if index == -1:
95 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
96 return ("", p)
Fred Drakeb4e460a2000-09-28 16:25:20 +000097 index = normp.find('\\', index + 1)
Guido van Rossum534972b1999-02-03 17:20:50 +000098 if index == -1:
99 index = len(p)
100 return p[:index], p[index:]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000101 return '', p
Guido van Rossum555915a1994-02-24 11:32:59 +0000102
103
104# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000105# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000106# join(head, tail) == p holds.
107# The resulting head won't end in '/' unless it is the root.
108
109def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000110 """Split a pathname.
111
112 Return tuple (head, tail) where tail is everything after the final slash.
113 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000114
Guido van Rossum15e22e11997-12-05 19:03:01 +0000115 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000116 # set i to index beyond p's last slash
117 i = len(p)
118 while i and p[i-1] not in '/\\':
119 i = i - 1
120 head, tail = p[:i], p[i:] # now tail has no slashes
121 # remove trailing slashes from head, unless it's all slashes
122 head2 = head
123 while head2 and head2[-1] in '/\\':
124 head2 = head2[:-1]
125 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000126 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000127
128
129# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000130# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000131# pathname component; the root is everything before that.
132# It is always true that root + ext == p.
133
134def splitext(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000135 """Split the extension from a pathname.
136
137 Extension is everything from the last dot to the end.
138 Return (root, ext), either part may be empty."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000139 root, ext = '', ''
140 for c in p:
141 if c in ['/','\\']:
142 root, ext = root + ext + c, ''
143 elif c == '.':
144 if ext:
145 root, ext = root + ext, c
146 else:
147 ext = c
148 elif ext:
149 ext = ext + c
150 else:
151 root = root + c
152 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000153
154
155# Return the tail (basename) part of a path.
156
157def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000158 """Returns the final component of a pathname"""
159 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000160
161
162# Return the head (dirname) part of a path.
163
164def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000165 """Returns the directory component of a pathname"""
166 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000167
168
169# Return the longest prefix of all list elements.
170
171def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000172 "Given a list of pathnames, returns the longest common leading component"
173 if not m: return ''
Skip Montanaro62358312000-08-22 13:01:53 +0000174 prefix = m[0]
175 for item in m:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000176 for i in range(len(prefix)):
Fred Drake8152d322000-12-12 23:20:45 +0000177 if prefix[:i+1] != item[:i+1]:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000178 prefix = prefix[:i]
179 if i == 0: return ''
180 break
Skip Montanaro62358312000-08-22 13:01:53 +0000181 return prefix
Guido van Rossum555915a1994-02-24 11:32:59 +0000182
183
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000184# Get size, mtime, atime of files.
185
186def getsize(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000187 """Return the size of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000188 st = os.stat(filename)
189 return st[stat.ST_SIZE]
190
191def getmtime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000192 """Return the last modification time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000193 st = os.stat(filename)
194 return st[stat.ST_MTIME]
195
196def getatime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000197 """Return the last access time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000198 st = os.stat(filename)
Fred Drake162bd852000-07-01 06:36:51 +0000199 return st[stat.ST_ATIME]
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000200
201
Guido van Rossum555915a1994-02-24 11:32:59 +0000202# Is a path a symbolic link?
203# This will always return false on systems where posix.lstat doesn't exist.
204
205def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000206 """Test for symbolic link. On WindowsNT/95 always returns false"""
207 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000208
209
210# Does a path exist?
211# This is false for dangling symbolic links.
212
213def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000214 """Test whether a path exists"""
215 try:
216 st = os.stat(path)
217 except os.error:
218 return 0
219 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000220
221
222# Is a path a dos directory?
223# This follows symbolic links, so both islink() and isdir() can be true
224# for the same path.
225
226def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000227 """Test whether a path is a directory"""
228 try:
229 st = os.stat(path)
230 except os.error:
231 return 0
232 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000233
234
235# Is a path a regular file?
236# This follows symbolic links, so both islink() and isdir() can be true
237# for the same path.
238
239def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000240 """Test whether a path is a regular file"""
241 try:
242 st = os.stat(path)
243 except os.error:
244 return 0
245 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000246
247
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000248# Is a path a mount point? Either a root (with or without drive letter)
249# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000250
251def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000252 """Test whether a path is a mount point (defined as root of drive)"""
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000253 unc, rest = splitunc(path)
254 if unc:
255 return rest in ("", "/", "\\")
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000256 p = splitdrive(path)[1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000257 return len(p) == 1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000258
259
260# Directory tree walk.
261# For each directory under top (including top itself, but excluding
262# '.' and '..'), func(arg, dirname, filenames) is called, where
263# dirname is the name of the directory and filenames is the list
264# files files (and subdirectories etc.) in the directory.
265# The func may modify the filenames list, to implement a filter,
266# or to impose a different order of visiting.
267
268def walk(top, func, arg):
Guido van Rossum534972b1999-02-03 17:20:50 +0000269 """Directory tree walk whth callback function.
270
Tim Peters2344fae2001-01-15 00:50:52 +0000271 walk(top, func, arg) calls func(arg, d, files) for each directory d
Guido van Rossum534972b1999-02-03 17:20:50 +0000272 in the tree rooted at top (including top itself); files is a list
273 of all the files and subdirs in directory d."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000274 try:
275 names = os.listdir(top)
276 except os.error:
277 return
278 func(arg, top, names)
279 exceptions = ('.', '..')
280 for name in names:
281 if name not in exceptions:
282 name = join(top, name)
283 if isdir(name):
284 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000285
286
287# Expand paths beginning with '~' or '~user'.
288# '~' means $HOME; '~user' means that user's home directory.
289# If the path doesn't begin with '~', or if the user or $HOME is unknown,
290# the path is returned unchanged (leaving error reporting to whatever
291# function is called with the expanded path as argument).
292# See also module 'glob' for expansion of *, ? and [...] in pathnames.
293# (A function should also be defined to do full *sh-style environment
294# variable expansion.)
295
296def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000297 """Expand ~ and ~user constructs.
298
299 If user or $HOME is unknown, do nothing."""
Fred Drake8152d322000-12-12 23:20:45 +0000300 if path[:1] != '~':
Guido van Rossum15e22e11997-12-05 19:03:01 +0000301 return path
302 i, n = 1, len(path)
303 while i < n and path[i] not in '/\\':
Fred Drakeb4e460a2000-09-28 16:25:20 +0000304 i = i + 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000305 if i == 1:
306 if os.environ.has_key('HOME'):
307 userhome = os.environ['HOME']
308 elif not os.environ.has_key('HOMEPATH'):
309 return path
310 else:
311 try:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000312 drive = os.environ['HOMEDRIVE']
Guido van Rossum15e22e11997-12-05 19:03:01 +0000313 except KeyError:
314 drive = ''
315 userhome = join(drive, os.environ['HOMEPATH'])
316 else:
317 return path
318 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000319
320
321# Expand paths containing shell variable substitutions.
322# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000323# - no expansion within single quotes
324# - no escape character, except for '$$' which is translated into '$'
325# - ${varname} is accepted.
326# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000327# XXX With COMMAND.COM you can use any characters in a variable name,
328# XXX except '^|<>='.
329
Tim Peters2344fae2001-01-15 00:50:52 +0000330def expandvars(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000331 """Expand shell variables of form $var and ${var}.
332
333 Unknown variables are left unchanged."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000334 if '$' not in path:
335 return path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000336 import string
Fred Drake79e75e12001-07-20 19:05:50 +0000337 varchars = string.ascii_letters + string.digits + '_-'
Guido van Rossum15e22e11997-12-05 19:03:01 +0000338 res = ''
339 index = 0
340 pathlen = len(path)
341 while index < pathlen:
342 c = path[index]
343 if c == '\'': # no expansion within single quotes
344 path = path[index + 1:]
345 pathlen = len(path)
346 try:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000347 index = path.index('\'')
Guido van Rossum15e22e11997-12-05 19:03:01 +0000348 res = res + '\'' + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000349 except ValueError:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000350 res = res + path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000351 index = pathlen - 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000352 elif c == '$': # variable or '$$'
353 if path[index + 1:index + 2] == '$':
354 res = res + c
355 index = index + 1
356 elif path[index + 1:index + 2] == '{':
357 path = path[index+2:]
358 pathlen = len(path)
359 try:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000360 index = path.index('}')
Guido van Rossum15e22e11997-12-05 19:03:01 +0000361 var = path[:index]
362 if os.environ.has_key(var):
363 res = res + os.environ[var]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000364 except ValueError:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000365 res = res + path
366 index = pathlen - 1
367 else:
368 var = ''
369 index = index + 1
370 c = path[index:index + 1]
371 while c != '' and c in varchars:
372 var = var + c
373 index = index + 1
374 c = path[index:index + 1]
375 if os.environ.has_key(var):
376 res = res + os.environ[var]
377 if c != '':
378 res = res + c
379 else:
380 res = res + c
381 index = index + 1
382 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000383
384
385# 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 +0000386# Previously, this function also truncated pathnames to 8+3 format,
387# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000388
389def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000390 """Normalize path, eliminating double slashes, etc."""
Fred Drakeb4e460a2000-09-28 16:25:20 +0000391 path = path.replace("/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000392 prefix, path = splitdrive(path)
Fred Drakeb4e460a2000-09-28 16:25:20 +0000393 while path[:1] == "\\":
394 prefix = prefix + "\\"
Guido van Rossum15e22e11997-12-05 19:03:01 +0000395 path = path[1:]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000396 comps = path.split("\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000397 i = 0
398 while i < len(comps):
399 if comps[i] == '.':
400 del comps[i]
401 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
402 del comps[i-1:i+1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000403 i = i - 1
Fred Drake8152d322000-12-12 23:20:45 +0000404 elif comps[i] == '' and i > 0 and comps[i-1] != '':
Guido van Rossum15e22e11997-12-05 19:03:01 +0000405 del comps[i]
406 else:
Fred Drakeb4e460a2000-09-28 16:25:20 +0000407 i = i + 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000408 # If the path is now empty, substitute '.'
409 if not prefix and not comps:
410 comps.append('.')
Fred Drakeb4e460a2000-09-28 16:25:20 +0000411 return prefix + "\\".join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000412
413
414# Return an absolute path.
415def abspath(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000416 """Return the absolute version of a path"""
Mark Hammond647d2fe2000-08-14 06:20:32 +0000417 if path: # Empty path must return current working directory.
Mark Hammondef8b6542001-05-13 08:04:26 +0000418 from nt import _getfullpathname
Mark Hammond647d2fe2000-08-14 06:20:32 +0000419 try:
Mark Hammondef8b6542001-05-13 08:04:26 +0000420 path = _getfullpathname(path)
421 except WindowsError:
Fred Drakeda05e972001-05-15 15:23:01 +0000422 pass # Bad path - return unchanged.
Mark Hammond647d2fe2000-08-14 06:20:32 +0000423 else:
424 path = os.getcwd()
Guido van Rossum6dfc7921999-11-30 15:00:00 +0000425 return normpath(path)