1 # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
2 """Common pathname manipulations, WindowsNT/95 version.
4 Instead of importing this module directly, import os and refer to this
11 __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"]
16 # Normalize the case of a pathname and map slashes to backslashes.
17 # Other normalizations (such as optimizing '../' away) are not done
18 # (this is done by normpath).
21 """Normalize case of pathname.
23 Makes all characters lowercase and all slashes into backslashes."""
24 return s
.replace("/", "\\").lower()
27 # Return whether a path is absolute.
28 # 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
30 # volume), or if a pathname after the volume letter and colon / UNC resource
31 # starts with a slash or backslash.
34 """Test whether a path is absolute"""
36 return s
!= '' and s
[:1] in '/\\'
39 # Join two (or more) paths.
42 """Join two or more pathname components, inserting "\\" as needed"""
45 b_wins
= 0 # set to 1 iff b makes path irrelevant
50 # This probably wipes out path so far. However, it's more
51 # complicated if path begins with a drive letter:
52 # 1. join('c:', '/a') == 'c:/a'
53 # 2. join('c:/', '/a') == 'c:/a'
55 # 3. join('c:/a', '/b') == '/b'
56 # 4. join('c:', 'd:/') = 'd:/'
57 # 5. join('c:/', 'd:/') = 'd:/'
58 if path
[1:2] != ":" or b
[1:2] == ":":
59 # Path doesn't start with a drive letter, or cases 4 and 5.
62 # Else path has a drive letter, and b doesn't but is absolute.
63 elif len(path
) > 3 or (len(path
) == 3 and
64 path
[-1] not in "/\\"):
71 # Join, and ensure there's a separator.
74 if b
and b
[0] in "/\\":
89 # Split a path in a drive specification (a drive letter followed by a
90 # colon) and the path specification.
91 # It is always true that drivespec + pathspec == p
93 """Split a pathname into drive and path specifiers. Returns a 2-tuple
94 "(drive,path)"; either part may be empty"""
102 """Split a pathname into UNC mount point and relative path specifiers.
104 Return a 2-tuple (unc, rest); either part may be empty.
105 If unc is not empty, it has the form '//host/mount' (or similar
106 using backslashes). unc+rest is always the input path.
107 Paths containing drive letters never have an UNC part.
110 return '', p
# Drive letter present
112 if firstTwo
== '//' or firstTwo
== '\\\\':
114 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
115 # \\machine\mountpoint\directories...
116 # directory ^^^^^^^^^^^^^^^
118 index
= normp
.find('\\', 2)
120 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
122 index
= normp
.find('\\', index
+ 1)
125 return p
[:index
], p
[index
:]
129 # Split a path in head (everything up to the last '/') and tail (the
130 # rest). After the trailing '/' is stripped, the invariant
131 # join(head, tail) == p holds.
132 # The resulting head won't end in '/' unless it is the root.
137 Return tuple (head, tail) where tail is everything after the final slash.
138 Either part may be empty."""
141 # set i to index beyond p's last slash
143 while i
and p
[i
-1] not in '/\\':
145 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
146 # remove trailing slashes from head, unless it's all slashes
148 while head2
and head2
[-1] in '/\\':
151 return d
+ head
, tail
154 # Split a path in root and extension.
155 # The extension is everything starting at the last dot in the last
156 # pathname component; the root is everything before that.
157 # It is always true that root + ext == p.
160 """Split the extension from a pathname.
162 Extension is everything from the last dot to the end.
163 Return (root, ext), either part may be empty."""
167 root
, ext
= root
+ ext
+ c
, ''
170 root
, ext
= root
+ ext
, c
180 # Return the tail (basename) part of a path.
183 """Returns the final component of a pathname"""
187 # Return the head (dirname) part of a path.
190 """Returns the directory component of a pathname"""
194 # Return the longest prefix of all list elements.
197 "Given a list of pathnames, returns the longest common leading component"
201 for i
in range(len(prefix
)):
202 if prefix
[:i
+1] != item
[:i
+1]:
209 # Get size, mtime, atime of files.
211 def getsize(filename
):
212 """Return the size of a file, reported by os.stat()"""
213 st
= os
.stat(filename
)
214 return st
[stat
.ST_SIZE
]
216 def getmtime(filename
):
217 """Return the last modification time of a file, reported by os.stat()"""
218 st
= os
.stat(filename
)
219 return st
[stat
.ST_MTIME
]
221 def getatime(filename
):
222 """Return the last access time of a file, reported by os.stat()"""
223 st
= os
.stat(filename
)
224 return st
[stat
.ST_ATIME
]
227 # Is a path a symbolic link?
228 # This will always return false on systems where posix.lstat doesn't exist.
231 """Test for symbolic link. On WindowsNT/95 always returns false"""
236 # This is false for dangling symbolic links.
239 """Test whether a path exists"""
247 # Is a path a dos directory?
248 # This follows symbolic links, so both islink() and isdir() can be true
252 """Test whether a path is a directory"""
257 return stat
.S_ISDIR(st
[stat
.ST_MODE
])
260 # Is a path a regular file?
261 # This follows symbolic links, so both islink() and isdir() can be true
265 """Test whether a path is a regular file"""
270 return stat
.S_ISREG(st
[stat
.ST_MODE
])
273 # Is a path a mount point? Either a root (with or without drive letter)
274 # or an UNC path with at most a / or \ after the mount point.
277 """Test whether a path is a mount point (defined as root of drive)"""
278 unc
, rest
= splitunc(path
)
280 return rest
in ("", "/", "\\")
281 p
= splitdrive(path
)[1]
282 return len(p
) == 1 and p
[0] in '/\\'
285 # Directory tree walk.
286 # For each directory under top (including top itself, but excluding
287 # '.' and '..'), func(arg, dirname, filenames) is called, where
288 # dirname is the name of the directory and filenames is the list
289 # files files (and subdirectories etc.) in the directory.
290 # The func may modify the filenames list, to implement a filter,
291 # or to impose a different order of visiting.
293 def walk(top
, func
, arg
):
294 """Directory tree walk whth callback function.
296 walk(top, func, arg) calls func(arg, d, files) for each directory d
297 in the tree rooted at top (including top itself); files is a list
298 of all the files and subdirs in directory d."""
300 names
= os
.listdir(top
)
303 func(arg
, top
, names
)
304 exceptions
= ('.', '..')
306 if name
not in exceptions
:
307 name
= join(top
, name
)
309 walk(name
, func
, arg
)
312 # Expand paths beginning with '~' or '~user'.
313 # '~' means $HOME; '~user' means that user's home directory.
314 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
315 # the path is returned unchanged (leaving error reporting to whatever
316 # function is called with the expanded path as argument).
317 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
318 # (A function should also be defined to do full *sh-style environment
319 # variable expansion.)
321 def expanduser(path
):
322 """Expand ~ and ~user constructs.
324 If user or $HOME is unknown, do nothing."""
328 while i
< n
and path
[i
] not in '/\\':
331 if os
.environ
.has_key('HOME'):
332 userhome
= os
.environ
['HOME']
333 elif not os
.environ
.has_key('HOMEPATH'):
337 drive
= os
.environ
['HOMEDRIVE']
340 userhome
= join(drive
, os
.environ
['HOMEPATH'])
343 return userhome
+ path
[i
:]
346 # Expand paths containing shell variable substitutions.
347 # The following rules apply:
348 # - no expansion within single quotes
349 # - no escape character, except for '$$' which is translated into '$'
350 # - ${varname} is accepted.
351 # - varnames can be made out of letters, digits and the character '_'
352 # XXX With COMMAND.COM you can use any characters in a variable name,
353 # XXX except '^|<>='.
355 def expandvars(path
):
356 """Expand shell variables of form $var and ${var}.
358 Unknown variables are left unchanged."""
362 varchars
= string
.ascii_letters
+ string
.digits
+ '_-'
366 while index
< pathlen
:
368 if c
== '\'': # no expansion within single quotes
369 path
= path
[index
+ 1:]
372 index
= path
.index('\'')
373 res
= res
+ '\'' + path
[:index
+ 1]
377 elif c
== '$': # variable or '$$'
378 if path
[index
+ 1:index
+ 2] == '$':
381 elif path
[index
+ 1:index
+ 2] == '{':
382 path
= path
[index
+2:]
385 index
= path
.index('}')
387 if os
.environ
.has_key(var
):
388 res
= res
+ os
.environ
[var
]
395 c
= path
[index
:index
+ 1]
396 while c
!= '' and c
in varchars
:
399 c
= path
[index
:index
+ 1]
400 if os
.environ
.has_key(var
):
401 res
= res
+ os
.environ
[var
]
410 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
411 # Previously, this function also truncated pathnames to 8+3 format,
412 # but as this module is called "ntpath", that's obviously wrong!
415 """Normalize path, eliminating double slashes, etc."""
416 path
= path
.replace("/", "\\")
417 prefix
, path
= splitdrive(path
)
418 while path
[:1] == "\\":
419 prefix
= prefix
+ "\\"
421 comps
= path
.split("\\")
423 while i
< len(comps
):
426 elif comps
[i
] == '..' and i
> 0 and comps
[i
-1] not in ('', '..'):
429 elif comps
[i
] == '' and i
> 0 and comps
[i
-1] != '':
433 # If the path is now empty, substitute '.'
434 if not prefix
and not comps
:
436 return prefix
+ "\\".join(comps
)
439 # Return an absolute path.
441 """Return the absolute version of a path"""
442 if path
: # Empty path must return current working directory.
443 from nt
import _getfullpathname
445 path
= _getfullpathname(path
)
447 pass # Bad path - return unchanged.
450 return normpath(path
)