blob: 5782cbe843fcbec99dc38bca767608577f9aba47 [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
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000146# Get size, mtime, atime of files.
147
148def getsize(filename):
149 """Return the size of a file, reported by os.stat()."""
150 st = os.stat(filename)
151 return st[stat.ST_SIZE]
152
153def getmtime(filename):
154 """Return the last modification time of a file, reported by os.stat()."""
155 st = os.stat(filename)
156 return st[stat.ST_MTIME]
157
158def getatime(filename):
159 """Return the last access time of a file, reported by os.stat()."""
160 st = os.stat(filename)
161 return st[stat.ST_MTIME]
162
163
Guido van Rossum555915a1994-02-24 11:32:59 +0000164# Is a path a symbolic link?
165# This will always return false on systems where posix.lstat doesn't exist.
166
167def islink(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000168 """Test for symbolic link. On WindowsNT/95 always returns false"""
169 return 0
Guido van Rossum555915a1994-02-24 11:32:59 +0000170
171
172# Does a path exist?
173# This is false for dangling symbolic links.
174
175def exists(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000176 """Test whether a path exists"""
177 try:
178 st = os.stat(path)
179 except os.error:
180 return 0
181 return 1
Guido van Rossum555915a1994-02-24 11:32:59 +0000182
183
184# Is a path a dos directory?
185# This follows symbolic links, so both islink() and isdir() can be true
186# for the same path.
187
188def isdir(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000189 """Test whether a path is a directory"""
190 try:
191 st = os.stat(path)
192 except os.error:
193 return 0
194 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000195
196
197# Is a path a regular file?
198# This follows symbolic links, so both islink() and isdir() can be true
199# for the same path.
200
201def isfile(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000202 """Test whether a path is a regular file"""
203 try:
204 st = os.stat(path)
205 except os.error:
206 return 0
207 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossum555915a1994-02-24 11:32:59 +0000208
209
Guido van Rossum555915a1994-02-24 11:32:59 +0000210# Is a path a mount point?
211# XXX This degenerates in: 'is this the root?' on DOS
212
213def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000214 """Test whether a path is a mount point (defined as root of drive)"""
215 p = splitdrive(path)[1]
216 return len(p)==1 and p[0] in '/\\'
Guido van Rossum555915a1994-02-24 11:32:59 +0000217
218
219# Directory tree walk.
220# For each directory under top (including top itself, but excluding
221# '.' and '..'), func(arg, dirname, filenames) is called, where
222# dirname is the name of the directory and filenames is the list
223# files files (and subdirectories etc.) in the directory.
224# The func may modify the filenames list, to implement a filter,
225# or to impose a different order of visiting.
226
227def walk(top, func, arg):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000228 """walk(top,func,args) calls func(arg, d, files) for each directory "d"
229in the tree rooted at "top" (including "top" itself). "files" is a list
230of all the files and subdirs in directory "d".
231"""
232 try:
233 names = os.listdir(top)
234 except os.error:
235 return
236 func(arg, top, names)
237 exceptions = ('.', '..')
238 for name in names:
239 if name not in exceptions:
240 name = join(top, name)
241 if isdir(name):
242 walk(name, func, arg)
Guido van Rossum555915a1994-02-24 11:32:59 +0000243
244
245# Expand paths beginning with '~' or '~user'.
246# '~' means $HOME; '~user' means that user's home directory.
247# If the path doesn't begin with '~', or if the user or $HOME is unknown,
248# the path is returned unchanged (leaving error reporting to whatever
249# function is called with the expanded path as argument).
250# See also module 'glob' for expansion of *, ? and [...] in pathnames.
251# (A function should also be defined to do full *sh-style environment
252# variable expansion.)
253
254def expanduser(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000255 """Expand ~ and ~user constructions. If user or $HOME is unknown,
256do nothing"""
257 if path[:1] <> '~':
258 return path
259 i, n = 1, len(path)
260 while i < n and path[i] not in '/\\':
261 i = i+1
262 if i == 1:
263 if os.environ.has_key('HOME'):
264 userhome = os.environ['HOME']
265 elif not os.environ.has_key('HOMEPATH'):
266 return path
267 else:
268 try:
269 drive=os.environ['HOMEDRIVE']
270 except KeyError:
271 drive = ''
272 userhome = join(drive, os.environ['HOMEPATH'])
273 else:
274 return path
275 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000276
277
278# Expand paths containing shell variable substitutions.
279# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000280# - no expansion within single quotes
281# - no escape character, except for '$$' which is translated into '$'
282# - ${varname} is accepted.
283# - varnames can be made out of letters, digits and the character '_'
Guido van Rossum555915a1994-02-24 11:32:59 +0000284# XXX With COMMAND.COM you can use any characters in a variable name,
285# XXX except '^|<>='.
286
287varchars = string.letters + string.digits + '_-'
288
Guido van Rossum15e22e11997-12-05 19:03:01 +0000289def expandvars(path):
290 """Expand shell variables of form $var and ${var}. Unknown variables
291are left unchanged"""
292 if '$' not in path:
293 return path
294 res = ''
295 index = 0
296 pathlen = len(path)
297 while index < pathlen:
298 c = path[index]
299 if c == '\'': # no expansion within single quotes
300 path = path[index + 1:]
301 pathlen = len(path)
302 try:
303 index = string.index(path, '\'')
304 res = res + '\'' + path[:index + 1]
305 except string.index_error:
306 res = res + path
307 index = pathlen -1
308 elif c == '$': # variable or '$$'
309 if path[index + 1:index + 2] == '$':
310 res = res + c
311 index = index + 1
312 elif path[index + 1:index + 2] == '{':
313 path = path[index+2:]
314 pathlen = len(path)
315 try:
316 index = string.index(path, '}')
317 var = path[:index]
318 if os.environ.has_key(var):
319 res = res + os.environ[var]
320 except string.index_error:
321 res = res + path
322 index = pathlen - 1
323 else:
324 var = ''
325 index = index + 1
326 c = path[index:index + 1]
327 while c != '' and c in varchars:
328 var = var + c
329 index = index + 1
330 c = path[index:index + 1]
331 if os.environ.has_key(var):
332 res = res + os.environ[var]
333 if c != '':
334 res = res + c
335 else:
336 res = res + c
337 index = index + 1
338 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000339
340
341# 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 +0000342# Previously, this function also truncated pathnames to 8+3 format,
343# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000344
345def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000346 """Normalize path, eliminating double slashes, etc."""
Guido van Rossum16a0bc21998-02-18 13:48:31 +0000347 path = string.replace(path, "/", "\\")
Guido van Rossum15e22e11997-12-05 19:03:01 +0000348 prefix, path = splitdrive(path)
349 while path[:1] == os.sep:
350 prefix = prefix + os.sep
351 path = path[1:]
352 comps = string.splitfields(path, os.sep)
353 i = 0
354 while i < len(comps):
355 if comps[i] == '.':
356 del comps[i]
357 elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
358 del comps[i-1:i+1]
359 i = i-1
360 elif comps[i] == '' and i > 0 and comps[i-1] <> '':
361 del comps[i]
362 else:
363 i = i+1
364 # If the path is now empty, substitute '.'
365 if not prefix and not comps:
366 comps.append('.')
367 return prefix + string.joinfields(comps, os.sep)
Guido van Rossume294cf61999-01-29 18:05:18 +0000368
369
370# Return an absolute path.
371def abspath(path):
Guido van Rossum9787bea1999-01-29 22:30:41 +0000372 try:
373 import win32api
374 return win32api.GetFullPathName(path)
375 except ImportError:
376 if not isabs(path):
377 path = join(os.getcwd(), path)
378 return normpath(path)