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
12 from genericpath
import *
14 __all__
= ["normcase","isabs","join","splitdrive","split","splitext",
15 "basename","dirname","commonprefix","getsize","getmtime",
16 "getatime","getctime", "islink","exists","lexists","isdir","isfile",
17 "ismount","walk","expanduser","expandvars","normpath","abspath",
18 "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
19 "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
21 # strings representing various path-related bits and pieces
29 if 'ce' in sys
.builtin_module_names
:
31 elif 'os2' in sys
.builtin_module_names
:
36 # Normalize the case of a pathname and map slashes to backslashes.
37 # Other normalizations (such as optimizing '../' away) are not done
38 # (this is done by normpath).
41 """Normalize case of pathname.
43 Makes all characters lowercase and all slashes into backslashes."""
44 return s
.replace("/", "\\").lower()
47 # Return whether a path is absolute.
48 # Trivial in Posix, harder on the Mac or MS-DOS.
49 # For DOS it is absolute if it starts with a slash or backslash (current
50 # volume), or if a pathname after the volume letter and colon / UNC resource
51 # starts with a slash or backslash.
54 """Test whether a path is absolute"""
56 return s
!= '' and s
[:1] in '/\\'
59 # Join two (or more) paths.
62 """Join two or more pathname components, inserting "\\" as needed.
63 If any component is an absolute path, all previous path components
67 b_wins
= 0 # set to 1 iff b makes path irrelevant
72 # This probably wipes out path so far. However, it's more
73 # complicated if path begins with a drive letter:
74 # 1. join('c:', '/a') == 'c:/a'
75 # 2. join('c:/', '/a') == 'c:/a'
77 # 3. join('c:/a', '/b') == '/b'
78 # 4. join('c:', 'd:/') = 'd:/'
79 # 5. join('c:/', 'd:/') = 'd:/'
80 if path
[1:2] != ":" or b
[1:2] == ":":
81 # Path doesn't start with a drive letter, or cases 4 and 5.
84 # Else path has a drive letter, and b doesn't but is absolute.
85 elif len(path
) > 3 or (len(path
) == 3 and
86 path
[-1] not in "/\\"):
93 # Join, and ensure there's a separator.
96 if b
and b
[0] in "/\\":
100 elif path
[-1] == ":":
108 # path is not empty and does not end with a backslash,
109 # but b is empty; since, e.g., split('a/') produces
110 # ('a', ''), it's best if join() adds a backslash in
117 # Split a path in a drive specification (a drive letter followed by a
118 # colon) and the path specification.
119 # It is always true that drivespec + pathspec == p
121 """Split a pathname into drive and path specifiers. Returns a 2-tuple
122 "(drive,path)"; either part may be empty"""
130 """Split a pathname into UNC mount point and relative path specifiers.
132 Return a 2-tuple (unc, rest); either part may be empty.
133 If unc is not empty, it has the form '//host/mount' (or similar
134 using backslashes). unc+rest is always the input path.
135 Paths containing drive letters never have an UNC part.
138 return '', p
# Drive letter present
140 if firstTwo
== '//' or firstTwo
== '\\\\':
142 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
143 # \\machine\mountpoint\directories...
144 # directory ^^^^^^^^^^^^^^^
146 index
= normp
.find('\\', 2)
148 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
150 index
= normp
.find('\\', index
+ 1)
153 return p
[:index
], p
[index
:]
157 # Split a path in head (everything up to the last '/') and tail (the
158 # rest). After the trailing '/' is stripped, the invariant
159 # join(head, tail) == p holds.
160 # The resulting head won't end in '/' unless it is the root.
165 Return tuple (head, tail) where tail is everything after the final slash.
166 Either part may be empty."""
169 # set i to index beyond p's last slash
171 while i
and p
[i
-1] not in '/\\':
173 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
174 # remove trailing slashes from head, unless it's all slashes
176 while head2
and head2
[-1] in '/\\':
179 return d
+ head
, tail
182 # Split a path in root and extension.
183 # The extension is everything starting at the last dot in the last
184 # pathname component; the root is everything before that.
185 # It is always true that root + ext == p.
188 return genericpath
._splitext
(p
, sep
, altsep
, extsep
)
189 splitext
.__doc
__ = genericpath
._splitext
.__doc
__
192 # Return the tail (basename) part of a path.
195 """Returns the final component of a pathname"""
199 # Return the head (dirname) part of a path.
202 """Returns the directory component of a pathname"""
205 # Is a path a symbolic link?
206 # This will always return false on systems where posix.lstat doesn't exist.
209 """Test for symbolic link.
210 On WindowsNT/95 and OS/2 always returns false
214 # alias exists to lexists
217 # Is a path a mount point? Either a root (with or without drive letter)
218 # or an UNC path with at most a / or \ after the mount point.
221 """Test whether a path is a mount point (defined as root of drive)"""
222 unc
, rest
= splitunc(path
)
224 return rest
in ("", "/", "\\")
225 p
= splitdrive(path
)[1]
226 return len(p
) == 1 and p
[0] in '/\\'
229 # Directory tree walk.
230 # For each directory under top (including top itself, but excluding
231 # '.' and '..'), func(arg, dirname, filenames) is called, where
232 # dirname is the name of the directory and filenames is the list
233 # of files (and subdirectories etc.) in the directory.
234 # The func may modify the filenames list, to implement a filter,
235 # or to impose a different order of visiting.
237 def walk(top
, func
, arg
):
238 """Directory tree walk with callback function.
240 For each directory in the directory tree rooted at top (including top
241 itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
242 dirname is the name of the directory, and fnames a list of the names of
243 the files and subdirectories in dirname (excluding '.' and '..'). func
244 may modify the fnames list in-place (e.g. via del or slice assignment),
245 and walk will only recurse into the subdirectories whose names remain in
246 fnames; this can be used to implement a filter, or to impose a specific
247 order of visiting. No semantics are defined for, or required of, arg,
248 beyond that arg is always passed to func. It can be used, e.g., to pass
249 a filename pattern, or a mutable object designed to accumulate
250 statistics. Passing None for arg is common."""
253 names
= os
.listdir(top
)
256 func(arg
, top
, names
)
257 exceptions
= ('.', '..')
259 if name
not in exceptions
:
260 name
= join(top
, name
)
262 walk(name
, func
, arg
)
265 # Expand paths beginning with '~' or '~user'.
266 # '~' means $HOME; '~user' means that user's home directory.
267 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
268 # the path is returned unchanged (leaving error reporting to whatever
269 # function is called with the expanded path as argument).
270 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
271 # (A function should also be defined to do full *sh-style environment
272 # variable expansion.)
274 def expanduser(path
):
275 """Expand ~ and ~user constructs.
277 If user or $HOME is unknown, do nothing."""
281 while i
< n
and path
[i
] not in '/\\':
284 if 'HOME' in os
.environ
:
285 userhome
= os
.environ
['HOME']
286 elif 'USERPROFILE' in os
.environ
:
287 userhome
= os
.environ
['USERPROFILE']
288 elif not 'HOMEPATH' in os
.environ
:
292 drive
= os
.environ
['HOMEDRIVE']
295 userhome
= join(drive
, os
.environ
['HOMEPATH'])
298 userhome
= join(dirname(userhome
), path
[1:i
])
300 return userhome
+ path
[i
:]
303 # Expand paths containing shell variable substitutions.
304 # The following rules apply:
305 # - no expansion within single quotes
306 # - '$$' is translated into '$'
307 # - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
308 # - ${varname} is accepted.
309 # - $varname is accepted.
310 # - %varname% is accepted.
311 # - varnames can be made out of letters, digits and the characters '_-'
312 # (though is not verifed in the ${varname} and %varname% cases)
313 # XXX With COMMAND.COM you can use any characters in a variable name,
314 # XXX except '^|<>='.
316 def expandvars(path
):
317 """Expand shell variables of the forms $var, ${var} and %var%.
319 Unknown variables are left unchanged."""
320 if '$' not in path
and '%' not in path
:
323 varchars
= string
.ascii_letters
+ string
.digits
+ '_-'
327 while index
< pathlen
:
329 if c
== '\'': # no expansion within single quotes
330 path
= path
[index
+ 1:]
333 index
= path
.index('\'')
334 res
= res
+ '\'' + path
[:index
+ 1]
338 elif c
== '%': # variable or '%'
339 if path
[index
+ 1:index
+ 2] == '%':
343 path
= path
[index
+1:]
346 index
= path
.index('%')
348 res
= res
+ '%' + path
352 if var
in os
.environ
:
353 res
= res
+ os
.environ
[var
]
355 res
= res
+ '%' + var
+ '%'
356 elif c
== '$': # variable or '$$'
357 if path
[index
+ 1:index
+ 2] == '$':
360 elif path
[index
+ 1:index
+ 2] == '{':
361 path
= path
[index
+2:]
364 index
= path
.index('}')
366 if var
in os
.environ
:
367 res
= res
+ os
.environ
[var
]
369 res
= res
+ '${' + var
+ '}'
371 res
= res
+ '${' + path
376 c
= path
[index
:index
+ 1]
377 while c
!= '' and c
in varchars
:
380 c
= path
[index
:index
+ 1]
381 if var
in os
.environ
:
382 res
= res
+ os
.environ
[var
]
384 res
= res
+ '$' + var
393 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
394 # Previously, this function also truncated pathnames to 8+3 format,
395 # but as this module is called "ntpath", that's obviously wrong!
398 """Normalize path, eliminating double slashes, etc."""
399 path
= path
.replace("/", "\\")
400 prefix
, path
= splitdrive(path
)
401 # We need to be careful here. If the prefix is empty, and the path starts
402 # with a backslash, it could either be an absolute path on the current
403 # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It
404 # is therefore imperative NOT to collapse multiple backslashes blindly in
406 # The code below preserves multiple backslashes when there is no drive
407 # letter. This means that the invalid filename \\\a\b is preserved
408 # unchanged, where a\\\b is normalised to a\b. It's not clear that there
409 # is any better behaviour for such edge cases.
411 # No drive letter - preserve initial backslashes
412 while path
[:1] == "\\":
413 prefix
= prefix
+ "\\"
416 # We have a drive letter - collapse initial backslashes
417 if path
.startswith("\\"):
418 prefix
= prefix
+ "\\"
419 path
= path
.lstrip("\\")
420 comps
= path
.split("\\")
422 while i
< len(comps
):
423 if comps
[i
] in ('.', ''):
425 elif comps
[i
] == '..':
426 if i
> 0 and comps
[i
-1] != '..':
429 elif i
== 0 and prefix
.endswith("\\"):
435 # If the path is now empty, substitute '.'
436 if not prefix
and not comps
:
438 return prefix
+ "\\".join(comps
)
441 # Return an absolute path.
443 from nt
import _getfullpathname
445 except ImportError: # not running on Windows - mock up something sensible
447 """Return the absolute version of a path."""
449 path
= join(os
.getcwd(), path
)
450 return normpath(path
)
452 else: # use native Windows method on Windows
454 """Return the absolute version of a path."""
456 if path
: # Empty path must return current working directory.
458 path
= _getfullpathname(path
)
460 pass # Bad path - return unchanged.
463 return normpath(path
)
465 # realpath is a no-op on systems without islink support
467 # Win9x family and earlier have no Unicode filename support.
468 supports_unicode_filenames
= (hasattr(sys
, "getwindowsversion") and
469 sys
.getwindowsversion()[3] >= 2)
471 def relpath(path
, start
=curdir
):
472 """Return a relative version of a path"""
475 raise ValueError("no path specified")
476 start_list
= abspath(start
).split(sep
)
477 path_list
= abspath(path
).split(sep
)
478 if start_list
[0].lower() != path_list
[0].lower():
479 unc_path
, rest
= splitunc(path
)
480 unc_start
, rest
= splitunc(start
)
481 if bool(unc_path
) ^
bool(unc_start
):
482 raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
485 raise ValueError("path is on drive %s, start on drive %s"
486 % (path_list
[0], start_list
[0]))
487 # Work out how much of the filepath is shared by start and path.
488 for i
in range(min(len(start_list
), len(path_list
))):
489 if start_list
[i
].lower() != path_list
[i
].lower():
494 rel_list
= [pardir
] * (len(start_list
)-i
) + path_list
[i
:]
495 return join(*rel_list
)