blob: 9597c63cd3f18f057f88a787bf5087865d5093b6 [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
80# rest). If the original path ends in '/' but is not the root, this
81# '/' is stripped. After the trailing '/' is stripped, the invariant
82# join(head, tail) == p holds.
83# The resulting head won't end in '/' unless it is the root.
84
85def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +000086 """Split a pathname.
87
88 Return tuple (head, tail) where tail is everything after the final slash.
89 Either part may be empty."""
Guido van Rossum15e22e11997-12-05 19:03:01 +000090 d, p = splitdrive(p)
91 slashes = ''
92 while p and p[-1:] in '/\\':
93 slashes = slashes + p[-1]
94 p = p[:-1]
95 if p == '':
96 p = p + slashes
97 head, tail = '', ''
98 for c in p:
99 tail = tail + c
100 if c in '/\\':
101 head, tail = head + tail, ''
102 slashes = ''
103 while head and head[-1:] in '/\\':
104 slashes = slashes + head[-1]
105 head = head[:-1]
106 if head == '':
107 head = head + slashes
108 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000109
110
111# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000112# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000113# pathname component; the root is everything before that.
114# It is always true that root + ext == p.
115
116def splitext(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000117 """Split the extension from a pathname.
118
119 Extension is everything from the last dot to the end.
120 Return (root, ext), either part may be empty."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000121 root, ext = '', ''
122 for c in p:
123 if c in ['/','\\']:
124 root, ext = root + ext + c, ''
125 elif c == '.':
126 if ext:
127 root, ext = root + ext, c
128 else:
129 ext = c
130 elif ext:
131 ext = ext + c
132 else:
133 root = root + c
134 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000135
136
137# Return the tail (basename) part of a path.
138
139def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000140 """Returns the final component of a pathname"""
141 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000142
143
144# Return the head (dirname) part of a path.
145
146def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000147 """Returns the directory component of a pathname"""
148 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000149
150
151# Return the longest prefix of all list elements.
152
153def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000154 "Given a list of pathnames, returns the longest common leading component"
155 if not m: return ''
156 prefix = m[0]
157 for item in m:
158 for i in range(len(prefix)):
159 if prefix[:i+1] <> item[:i+1]:
160 prefix = prefix[:i]
161 if i == 0: return ''
162 break
163 return prefix
Guido van Rossum555915a1994-02-24 11:32:59 +0000164
165
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000166# Get size, mtime, atime of files.
167
168def getsize(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000169 """Return the size of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000170 st = os.stat(filename)
171 return st[stat.ST_SIZE]
172
173def getmtime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000174 """Return the last modification time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000175 st = os.stat(filename)
176 return st[stat.ST_MTIME]
177
178def getatime(filename):
Guido van Rossum534972b1999-02-03 17:20:50 +0000179 """Return the last access time of a file, reported by os.stat()"""
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000180 st = os.stat(filename)
181 return st[stat.ST_MTIME]
182
183
Guido van Rossum555915a1994-02-24 11:32:59 +0000184# Is a path a symbolic link?
185# This will always return false on systems where posix.lstat doesn't exist.
186
187def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000188 """Test for symbolic link. On WindowsNT/95 always returns false"""
189 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000190
191
192# Does a path exist?
193# This is false for dangling symbolic links.
194
195def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000196 """Test whether a path exists"""
197 try:
198 st = os.stat(path)
199 except os.error:
200 return 0
201 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000202
203
204# Is a path a dos directory?
205# This follows symbolic links, so both islink() and isdir() can be true
206# for the same path.
207
208def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000209 """Test whether a path is a directory"""
210 try:
211 st = os.stat(path)
212 except os.error:
213 return 0
214 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000215
216
217# Is a path a regular file?
218# This follows symbolic links, so both islink() and isdir() can be true
219# for the same path.
220
221def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000222 """Test whether a path is a regular file"""
223 try:
224 st = os.stat(path)
225 except os.error:
226 return 0
227 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000228
229
Guido van Rossum555915a1994-02-24 11:32:59 +0000230# Is a path a mount point?
Guido van Rossum534972b1999-02-03 17:20:50 +0000231# XXX This degenerates in: 'is this the root?' on DOS/Windows
Guido van Rossum555915a1994-02-24 11:32:59 +0000232
233def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000234 """Test whether a path is a mount point (defined as root of drive)"""
235 p = splitdrive(path)[1]
236 return len(p)==1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000237
238
239# Directory tree walk.
240# For each directory under top (including top itself, but excluding
241# '.' and '..'), func(arg, dirname, filenames) is called, where
242# dirname is the name of the directory and filenames is the list
243# files files (and subdirectories etc.) in the directory.
244# The func may modify the filenames list, to implement a filter,
245# or to impose a different order of visiting.
246
247def walk(top, func, arg):
Guido van Rossum534972b1999-02-03 17:20:50 +0000248 """Directory tree walk whth callback function.
249
250 walk(top, func, args) calls func(arg, d, files) for each directory d
251 in the tree rooted at top (including top itself); files is a list
252 of all the files and subdirs in directory d."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000253 try:
254 names = os.listdir(top)
255 except os.error:
256 return
257 func(arg, top, names)
258 exceptions = ('.', '..')
259 for name in names:
260 if name not in exceptions:
261 name = join(top, name)
262 if isdir(name):
263 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000264
265
266# Expand paths beginning with '~' or '~user'.
267# '~' means $HOME; '~user' means that user's home directory.
268# If the path doesn't begin with '~', or if the user or $HOME is unknown,
269# the path is returned unchanged (leaving error reporting to whatever
270# function is called with the expanded path as argument).
271# See also module 'glob' for expansion of *, ? and [...] in pathnames.
272# (A function should also be defined to do full *sh-style environment
273# variable expansion.)
274
275def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000276 """Expand ~ and ~user constructs.
277
278 If user or $HOME is unknown, do nothing."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000279 if path[:1] <> '~':
280 return path
281 i, n = 1, len(path)
282 while i < n and path[i] not in '/\\':
283 i = i+1
284 if i == 1:
285 if os.environ.has_key('HOME'):
286 userhome = os.environ['HOME']
287 elif not os.environ.has_key('HOMEPATH'):
288 return path
289 else:
290 try:
291 drive=os.environ['HOMEDRIVE']
292 except KeyError:
293 drive = ''
294 userhome = join(drive, os.environ['HOMEPATH'])
295 else:
296 return path
297 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000298
299
300# Expand paths containing shell variable substitutions.
301# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000302# - no expansion within single quotes
303# - no escape character, except for '$$' which is translated into '$'
304# - ${varname} is accepted.
305# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000306# XXX With COMMAND.COM you can use any characters in a variable name,
307# XXX except '^|<>='.
308
309varchars = string.letters + string.digits + '_-'
310
Guido van Rossum15e22e11997-12-05 19:03:01 +0000311def expandvars(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000312 """Expand shell variables of form $var and ${var}.
313
314 Unknown variables are left unchanged."""
Guido van Rossum15e22e11997-12-05 19:03:01 +0000315 if '$' not in path:
316 return path
317 res = ''
318 index = 0
319 pathlen = len(path)
320 while index < pathlen:
321 c = path[index]
322 if c == '\'': # no expansion within single quotes
323 path = path[index + 1:]
324 pathlen = len(path)
325 try:
326 index = string.index(path, '\'')
327 res = res + '\'' + path[:index + 1]
328 except string.index_error:
329 res = res + path
330 index = pathlen -1
331 elif c == '$': # variable or '$$'
332 if path[index + 1:index + 2] == '$':
333 res = res + c
334 index = index + 1
335 elif path[index + 1:index + 2] == '{':
336 path = path[index+2:]
337 pathlen = len(path)
338 try:
339 index = string.index(path, '}')
340 var = path[:index]
341 if os.environ.has_key(var):
342 res = res + os.environ[var]
343 except string.index_error:
344 res = res + path
345 index = pathlen - 1
346 else:
347 var = ''
348 index = index + 1
349 c = path[index:index + 1]
350 while c != '' and c in varchars:
351 var = var + c
352 index = index + 1
353 c = path[index:index + 1]
354 if os.environ.has_key(var):
355 res = res + os.environ[var]
356 if c != '':
357 res = res + c
358 else:
359 res = res + c
360 index = index + 1
361 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000362
363
364# 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 +0000365# Previously, this function also truncated pathnames to 8+3 format,
366# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000367
368def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000369 """Normalize path, eliminating double slashes, etc."""
Guido van Rossum16a0bc21998-02-18 13:48:31 +0000370 path = string.replace(path, "/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000371 prefix, path = splitdrive(path)
372 while path[:1] == os.sep:
373 prefix = prefix + os.sep
374 path = path[1:]
375 comps = string.splitfields(path, os.sep)
376 i = 0
377 while i < len(comps):
378 if comps[i] == '.':
379 del comps[i]
380 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
381 del comps[i-1:i+1]
382 i = i-1
383 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
384 del comps[i]
385 else:
386 i = i+1
387 # If the path is now empty, substitute '.'
388 if not prefix and not comps:
389 comps.append('.')
390 return prefix + string.joinfields(comps, os.sep)
Guido van Rossume294cf61999-01-29 18:05:18 +0000391
392
393# Return an absolute path.
394def abspath(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000395 """Return the absolute version of a path"""
Guido van Rossum9787bea1999-01-29 22:30:41 +0000396 try:
397 import win32api
398 return win32api.GetFullPathName(path)
399 except ImportError:
400 if not isabs(path):
401 path = join(os.getcwd(), path)
402 return normpath(path)