blob: 2543890c35e1f8ef1f587788134d816f393d545e [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.
3Instead of importing this module
4directly, import os and refer to this module as os.path.
5"""
Guido van Rossum555915a1994-02-24 11:32:59 +00006
7import os
8import stat
9import string
10
11
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
19 Makes all characters lowercase and all slashes into backslashes.
20
21 """
22 return string.lower(string.replace(s, "/", "\\"))
Guido van Rossum555915a1994-02-24 11:32:59 +000023
Guido van Rossum77e1db31997-06-02 23:11:57 +000024
Guido van Rossum555915a1994-02-24 11:32:59 +000025# Return wheter a path is absolute.
26# Trivial in Posix, harder on the Mac or MS-DOS.
27# For DOS it is absolute if it starts with a slash or backslash (current
28# volume), or if a pathname after the volume letter and colon starts with
29# a slash or backslash.
30
31def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000032 """Test whether a path is absolute"""
33 s = splitdrive(s)[1]
34 return s != '' and s[:1] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +000035
36
Guido van Rossum77e1db31997-06-02 23:11:57 +000037# Join two (or more) paths.
38
Barry Warsaw384d2491997-02-18 21:53:25 +000039def join(a, *p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000040 """Join two or more pathname components, inserting "\\" as needed"""
41 path = a
42 for b in p:
43 if isabs(b):
44 path = b
45 elif path == '' or path[-1:] in '/\\':
46 path = path + b
47 else:
48 path = path + os.sep + b
49 return path
Guido van Rossum555915a1994-02-24 11:32:59 +000050
51
52# Split a path in a drive specification (a drive letter followed by a
53# colon) and the path specification.
54# It is always true that drivespec + pathspec == p
55def splitdrive(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000056 """Split a pathname into drive and path specifiers. Returns a 2-tuple
57"(drive,path)"; either part may be empty"""
58 if p[1:2] == ':':
59 return p[0:2], p[2:]
60 return '', p
Guido van Rossum555915a1994-02-24 11:32:59 +000061
62
63# Split a path in head (everything up to the last '/') and tail (the
64# rest). If the original path ends in '/' but is not the root, this
65# '/' is stripped. After the trailing '/' is stripped, the invariant
66# join(head, tail) == p holds.
67# The resulting head won't end in '/' unless it is the root.
68
69def split(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000070 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
71everything after the final slash. Either part may be empty"""
72 d, p = splitdrive(p)
73 slashes = ''
74 while p and p[-1:] in '/\\':
75 slashes = slashes + p[-1]
76 p = p[:-1]
77 if p == '':
78 p = p + slashes
79 head, tail = '', ''
80 for c in p:
81 tail = tail + c
82 if c in '/\\':
83 head, tail = head + tail, ''
84 slashes = ''
85 while head and head[-1:] in '/\\':
86 slashes = slashes + head[-1]
87 head = head[:-1]
88 if head == '':
89 head = head + slashes
90 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +000091
92
93# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +000094# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +000095# pathname component; the root is everything before that.
96# It is always true that root + ext == p.
97
98def splitext(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +000099 """Split the extension from a pathname. Extension is everything from the
100last dot to the end. Returns "(root, ext)", either part may be empty"""
101 root, ext = '', ''
102 for c in p:
103 if c in ['/','\\']:
104 root, ext = root + ext + c, ''
105 elif c == '.':
106 if ext:
107 root, ext = root + ext, c
108 else:
109 ext = c
110 elif ext:
111 ext = ext + c
112 else:
113 root = root + c
114 return root, ext
Guido van Rossum555915a1994-02-24 11:32:59 +0000115
116
117# Return the tail (basename) part of a path.
118
119def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000120 """Returns the final component of a pathname"""
121 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000122
123
124# Return the head (dirname) part of a path.
125
126def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000127 """Returns the directory component of a pathname"""
128 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000129
130
131# Return the longest prefix of all list elements.
132
133def commonprefix(m):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000134 "Given a list of pathnames, returns the longest common leading component"
135 if not m: return ''
136 prefix = m[0]
137 for item in m:
138 for i in range(len(prefix)):
139 if prefix[:i+1] <> item[:i+1]:
140 prefix = prefix[:i]
141 if i == 0: return ''
142 break
143 return prefix
Guido van Rossum555915a1994-02-24 11:32:59 +0000144
145
146# Is a path a symbolic link?
147# This will always return false on systems where posix.lstat doesn't exist.
148
149def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000150 """Test for symbolic link. On WindowsNT/95 always returns false"""
151 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000152
153
154# Does a path exist?
155# This is false for dangling symbolic links.
156
157def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000158 """Test whether a path exists"""
159 try:
160 st = os.stat(path)
161 except os.error:
162 return 0
163 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000164
165
166# Is a path a dos directory?
167# This follows symbolic links, so both islink() and isdir() can be true
168# for the same path.
169
170def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000171 """Test whether a path is a directory"""
172 try:
173 st = os.stat(path)
174 except os.error:
175 return 0
176 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000177
178
179# Is a path a regular file?
180# This follows symbolic links, so both islink() and isdir() can be true
181# for the same path.
182
183def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000184 """Test whether a path is a regular file"""
185 try:
186 st = os.stat(path)
187 except os.error:
188 return 0
189 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000190
191
192# Are two filenames really pointing to the same file?
193
194def samefile(f1, f2):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000195 """Test whether two pathnames reference the same actual file"""
196 s1 = os.stat(f1)
197 s2 = os.stat(f2)
198 return samestat(s1, s2)
Guido van Rossum555915a1994-02-24 11:32:59 +0000199
200
201# Are two open files really referencing the same file?
202# (Not necessarily the same file descriptor!)
203# XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads?
204
205def sameopenfile(fp1, fp2):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000206 """Test whether two open file objects reference the same file (may not
207work correctly)"""
208 s1 = os.fstat(fp1.fileno())
209 s2 = os.fstat(fp2.fileno())
210 return samestat(s1, s2)
Guido van Rossum555915a1994-02-24 11:32:59 +0000211
212
213# Are two stat buffers (obtained from stat, fstat or lstat)
214# describing the same file?
215
216def samestat(s1, s2):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000217 """Test whether two stat buffers reference the same file"""
218 return s1[stat.ST_INO] == s2[stat.ST_INO] and \
219 s1[stat.ST_DEV] == s2[stat.ST_DEV]
Guido van Rossum555915a1994-02-24 11:32:59 +0000220
221
222# Is a path a mount point?
223# XXX This degenerates in: 'is this the root?' on DOS
224
225def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000226 """Test whether a path is a mount point (defined as root of drive)"""
227 p = splitdrive(path)[1]
228 return len(p)==1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000229
230
231# Directory tree walk.
232# For each directory under top (including top itself, but excluding
233# '.' and '..'), func(arg, dirname, filenames) is called, where
234# dirname is the name of the directory and filenames is the list
235# files files (and subdirectories etc.) in the directory.
236# The func may modify the filenames list, to implement a filter,
237# or to impose a different order of visiting.
238
239def walk(top, func, arg):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000240 """walk(top,func,args) calls func(arg, d, files) for each directory "d"
241in the tree rooted at "top" (including "top" itself). "files" is a list
242of all the files and subdirs in directory "d".
243"""
244 try:
245 names = os.listdir(top)
246 except os.error:
247 return
248 func(arg, top, names)
249 exceptions = ('.', '..')
250 for name in names:
251 if name not in exceptions:
252 name = join(top, name)
253 if isdir(name):
254 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000255
256
257# Expand paths beginning with '~' or '~user'.
258# '~' means $HOME; '~user' means that user's home directory.
259# If the path doesn't begin with '~', or if the user or $HOME is unknown,
260# the path is returned unchanged (leaving error reporting to whatever
261# function is called with the expanded path as argument).
262# See also module 'glob' for expansion of *, ? and [...] in pathnames.
263# (A function should also be defined to do full *sh-style environment
264# variable expansion.)
265
266def expanduser(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000267 """Expand ~ and ~user constructions. If user or $HOME is unknown,
268do nothing"""
269 if path[:1] <> '~':
270 return path
271 i, n = 1, len(path)
272 while i < n and path[i] not in '/\\':
273 i = i+1
274 if i == 1:
275 if os.environ.has_key('HOME'):
276 userhome = os.environ['HOME']
277 elif not os.environ.has_key('HOMEPATH'):
278 return path
279 else:
280 try:
281 drive=os.environ['HOMEDRIVE']
282 except KeyError:
283 drive = ''
284 userhome = join(drive, os.environ['HOMEPATH'])
285 else:
286 return path
287 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000288
289
290# Expand paths containing shell variable substitutions.
291# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000292# - no expansion within single quotes
293# - no escape character, except for '$$' which is translated into '$'
294# - ${varname} is accepted.
295# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000296# XXX With COMMAND.COM you can use any characters in a variable name,
297# XXX except '^|<>='.
298
299varchars = string.letters + string.digits + '_-'
300
Guido van Rossum15e22e11997-12-05 19:03:01 +0000301def expandvars(path):
302 """Expand shell variables of form $var and ${var}. Unknown variables
303are left unchanged"""
304 if '$' not in path:
305 return path
306 res = ''
307 index = 0
308 pathlen = len(path)
309 while index < pathlen:
310 c = path[index]
311 if c == '\'': # no expansion within single quotes
312 path = path[index + 1:]
313 pathlen = len(path)
314 try:
315 index = string.index(path, '\'')
316 res = res + '\'' + path[:index + 1]
317 except string.index_error:
318 res = res + path
319 index = pathlen -1
320 elif c == '$': # variable or '$$'
321 if path[index + 1:index + 2] == '$':
322 res = res + c
323 index = index + 1
324 elif path[index + 1:index + 2] == '{':
325 path = path[index+2:]
326 pathlen = len(path)
327 try:
328 index = string.index(path, '}')
329 var = path[:index]
330 if os.environ.has_key(var):
331 res = res + os.environ[var]
332 except string.index_error:
333 res = res + path
334 index = pathlen - 1
335 else:
336 var = ''
337 index = index + 1
338 c = path[index:index + 1]
339 while c != '' and c in varchars:
340 var = var + c
341 index = index + 1
342 c = path[index:index + 1]
343 if os.environ.has_key(var):
344 res = res + os.environ[var]
345 if c != '':
346 res = res + c
347 else:
348 res = res + c
349 index = index + 1
350 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000351
352
353# 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 +0000354# Previously, this function also truncated pathnames to 8+3 format,
355# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000356
357def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000358 """Normalize path, eliminating double slashes, etc."""
Guido van Rossum16a0bc21998-02-18 13:48:31 +0000359 path = string.replace(path, "/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000360 prefix, path = splitdrive(path)
361 while path[:1] == os.sep:
362 prefix = prefix + os.sep
363 path = path[1:]
364 comps = string.splitfields(path, os.sep)
365 i = 0
366 while i < len(comps):
367 if comps[i] == '.':
368 del comps[i]
369 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
370 del comps[i-1:i+1]
371 i = i-1
372 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
373 del comps[i]
374 else:
375 i = i+1
376 # If the path is now empty, substitute '.'
377 if not prefix and not comps:
378 comps.append('.')
379 return prefix + string.joinfields(comps, os.sep)