blob: a74cce3ff23e8a90e26b8424a4a744868806d818 [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
11
12
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
Guido van Rossum555915a1994-02-24 11:32:59 +000024# Return wheter a path is absolute.
25# 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 Rossum534972b1999-02-03 17:20:50 +000052# colon, or a UNC resource) 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 Rossum534972b1999-02-03 17:20:50 +000055 """Split a pathname into drive and path specifiers.
56
57 Return a 2-tuple (drive, path); either part may be empty.
58 This recognizes UNC paths (e.g. '\\\\host\\mountpoint\\dir\\file')"""
Guido van Rossum15e22e11997-12-05 19:03:01 +000059 if p[1:2] == ':':
60 return p[0:2], p[2:]
Guido van Rossum534972b1999-02-03 17:20:50 +000061 firstTwo = p[0:2]
62 if firstTwo == '//' or firstTwo == '\\\\':
63 # is a UNC path:
64 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
65 # \\machine\mountpoint\directories...
66 # directory ^^^^^^^^^^^^^^^
67 normp = normcase(p)
68 index = string.find(normp, '\\', 2)
69 if index == -1:
70 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
71 return ("", p)
72 index = string.find(normp, '\\', index + 1)
73 if index == -1:
74 index = len(p)
75 return p[:index], p[index:]
Guido van Rossum15e22e11997-12-05 19:03:01 +000076 return '', p
Guido van Rossum555915a1994-02-24 11:32:59 +000077
78
79# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +000080# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +000081# join(head, tail) == p holds.
82# The resulting head won't end in '/' unless it is the root.
83
84def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +000085 """Split a pathname.
86
87 Return tuple (head, tail) where tail is everything after the final slash.
88 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +000089
Guido van Rossum15e22e11997-12-05 19:03:01 +000090 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +000091 # set i to index beyond p's last slash
92 i = len(p)
93 while i and p[i-1] not in '/\\':
94 i = i - 1
95 head, tail = p[:i], p[i:] # now tail has no slashes
96 # remove trailing slashes from head, unless it's all slashes
97 head2 = head
98 while head2 and head2[-1] in '/\\':
99 head2 = head2[:-1]
100 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000101 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000102
103
104# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000105# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000106# pathname component; the root is everything before that.
107# It is always true that root + ext == p.
108
109def splitext(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000110 """Split the extension from a pathname.
111
112 Extension is everything from the last dot to the end.
113 Return (root, ext), either part may be empty."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000114 root, ext = '', ''
115 for c in p:
116 if c in ['/','\\']:
117 root, ext = root + ext + c, ''
118 elif c == '.':
119 if ext:
120 root, ext = root + ext, c
121 else:
122 ext = c
123 elif ext:
124 ext = ext + c
125 else:
126 root = root + c
127 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000128
129
130# Return the tail (basename) part of a path.
131
132def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000133 """Returns the final component of a pathname"""
134 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000135
136
137# Return the head (dirname) part of a path.
138
139def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000140 """Returns the directory component of a pathname"""
141 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000142
143
144# Return the longest prefix of all list elements.
145
146def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000147 "Given a list of pathnames, returns the longest common leading component"
148 if not m: return ''
149 prefix = m[0]
150 for item in m:
151 for i in range(len(prefix)):
152 if prefix[:i+1] <> item[:i+1]:
153 prefix = prefix[:i]
154 if i == 0: return ''
155 break
156 return prefix
Guido van Rossum555915a1994-02-24 11:32:59 +0000157
158
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000159# Get size, mtime, atime of files.
160
161def getsize(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000162 """Return the size of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000163 st = os.stat(filename)
164 return st[stat.ST_SIZE]
165
166def getmtime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000167 """Return the last modification time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000168 st = os.stat(filename)
169 return st[stat.ST_MTIME]
170
171def getatime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000172 """Return the last access time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000173 st = os.stat(filename)
174 return st[stat.ST_MTIME]
175
176
Guido van Rossum555915a1994-02-24 11:32:59 +0000177# Is a path a symbolic link?
178# This will always return false on systems where posix.lstat doesn't exist.
179
180def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000181 """Test for symbolic link. On WindowsNT/95 always returns false"""
182 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000183
184
185# Does a path exist?
186# This is false for dangling symbolic links.
187
188def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000189 """Test whether a path exists"""
190 try:
191 st = os.stat(path)
192 except os.error:
193 return 0
194 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000195
196
197# Is a path a dos directory?
198# This follows symbolic links, so both islink() and isdir() can be true
199# for the same path.
200
201def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000202 """Test whether a path is a directory"""
203 try:
204 st = os.stat(path)
205 except os.error:
206 return 0
207 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000208
209
210# Is a path a regular file?
211# This follows symbolic links, so both islink() and isdir() can be true
212# for the same path.
213
214def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000215 """Test whether a path is a regular file"""
216 try:
217 st = os.stat(path)
218 except os.error:
219 return 0
220 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000221
222
Guido van Rossum555915a1994-02-24 11:32:59 +0000223# Is a path a mount point?
Guido van Rossum534972b1999-02-03 17:20:50 +0000224# XXX This degenerates in: 'is this the root?' on DOS/Windows
Guido van Rossum555915a1994-02-24 11:32:59 +0000225
226def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000227 """Test whether a path is a mount point (defined as root of drive)"""
228 p = splitdrive(path)[1]
229 return len(p)==1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000230
231
232# Directory tree walk.
233# For each directory under top (including top itself, but excluding
234# '.' and '..'), func(arg, dirname, filenames) is called, where
235# dirname is the name of the directory and filenames is the list
236# files files (and subdirectories etc.) in the directory.
237# The func may modify the filenames list, to implement a filter,
238# or to impose a different order of visiting.
239
240def walk(top, func, arg):
Guido van Rossum534972b1999-02-03 17:20:50 +0000241 """Directory tree walk whth callback function.
242
243 walk(top, func, args) calls func(arg, d, files) for each directory d
244 in the tree rooted at top (including top itself); files is a list
245 of all the files and subdirs in directory d."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000246 try:
247 names = os.listdir(top)
248 except os.error:
249 return
250 func(arg, top, names)
251 exceptions = ('.', '..')
252 for name in names:
253 if name not in exceptions:
254 name = join(top, name)
255 if isdir(name):
256 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000257
258
259# Expand paths beginning with '~' or '~user'.
260# '~' means $HOME; '~user' means that user's home directory.
261# If the path doesn't begin with '~', or if the user or $HOME is unknown,
262# the path is returned unchanged (leaving error reporting to whatever
263# function is called with the expanded path as argument).
264# See also module 'glob' for expansion of *, ? and [...] in pathnames.
265# (A function should also be defined to do full *sh-style environment
266# variable expansion.)
267
268def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000269 """Expand ~ and ~user constructs.
270
271 If user or $HOME is unknown, do nothing."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000272 if path[:1] <> '~':
273 return path
274 i, n = 1, len(path)
275 while i < n and path[i] not in '/\\':
276 i = i+1
277 if i == 1:
278 if os.environ.has_key('HOME'):
279 userhome = os.environ['HOME']
280 elif not os.environ.has_key('HOMEPATH'):
281 return path
282 else:
283 try:
284 drive=os.environ['HOMEDRIVE']
285 except KeyError:
286 drive = ''
287 userhome = join(drive, os.environ['HOMEPATH'])
288 else:
289 return path
290 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000291
292
293# Expand paths containing shell variable substitutions.
294# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000295# - no expansion within single quotes
296# - no escape character, except for '$$' which is translated into '$'
297# - ${varname} is accepted.
298# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000299# XXX With COMMAND.COM you can use any characters in a variable name,
300# XXX except '^|<>='.
301
302varchars = string.letters + string.digits + '_-'
303
Guido van Rossum15e22e11997-12-05 19:03:01 +0000304def expandvars(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000305 """Expand shell variables of form $var and ${var}.
306
307 Unknown variables are left unchanged."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000308 if '$' not in path:
309 return path
310 res = ''
311 index = 0
312 pathlen = len(path)
313 while index < pathlen:
314 c = path[index]
315 if c == '\'': # no expansion within single quotes
316 path = path[index + 1:]
317 pathlen = len(path)
318 try:
319 index = string.index(path, '\'')
320 res = res + '\'' + path[:index + 1]
321 except string.index_error:
322 res = res + path
323 index = pathlen -1
324 elif c == '$': # variable or '$$'
325 if path[index + 1:index + 2] == '$':
326 res = res + c
327 index = index + 1
328 elif path[index + 1:index + 2] == '{':
329 path = path[index+2:]
330 pathlen = len(path)
331 try:
332 index = string.index(path, '}')
333 var = path[:index]
334 if os.environ.has_key(var):
335 res = res + os.environ[var]
336 except string.index_error:
337 res = res + path
338 index = pathlen - 1
339 else:
340 var = ''
341 index = index + 1
342 c = path[index:index + 1]
343 while c != '' and c in varchars:
344 var = var + c
345 index = index + 1
346 c = path[index:index + 1]
347 if os.environ.has_key(var):
348 res = res + os.environ[var]
349 if c != '':
350 res = res + c
351 else:
352 res = res + c
353 index = index + 1
354 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000355
356
357# 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 +0000358# Previously, this function also truncated pathnames to 8+3 format,
359# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000360
361def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000362 """Normalize path, eliminating double slashes, etc."""
Guido van Rossum16a0bc21998-02-18 13:48:31 +0000363 path = string.replace(path, "/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000364 prefix, path = splitdrive(path)
365 while path[:1] == os.sep:
366 prefix = prefix + os.sep
367 path = path[1:]
368 comps = string.splitfields(path, os.sep)
369 i = 0
370 while i < len(comps):
371 if comps[i] == '.':
372 del comps[i]
373 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
374 del comps[i-1:i+1]
375 i = i-1
376 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
377 del comps[i]
378 else:
379 i = i+1
380 # If the path is now empty, substitute '.'
381 if not prefix and not comps:
382 comps.append('.')
383 return prefix + string.joinfields(comps, os.sep)
Guido van Rossume294cf61999-01-29 18:05:18 +0000384
385
386# Return an absolute path.
387def abspath(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000388 """Return the absolute version of a path"""
Guido van Rossum9787bea1999-01-29 22:30:41 +0000389 try:
390 import win32api
391 return win32api.GetFullPathName(path)
392 except ImportError:
393 if not isabs(path):
394 path = join(os.getcwd(), path)
395 return normpath(path)