# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
"""Common pathname manipulations, WindowsNT/95 version.
Instead of importing this module directly, import os and refer to this
__all__
= ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","getctime", "islink","exists","lexists","isdir","isfile",
"ismount","walk","expanduser","expandvars","normpath","abspath",
"splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
"extsep","devnull","realpath","supports_unicode_filenames"]
# strings representing various path-related bits and pieces
if 'ce' in sys
.builtin_module_names
:
elif 'os2' in sys
.builtin_module_names
:
# Normalize the case of a pathname and map slashes to backslashes.
# Other normalizations (such as optimizing '../' away) are not done
# (this is done by normpath).
"""Normalize case of pathname.
Makes all characters lowercase and all slashes into backslashes."""
return s
.replace("/", "\\").lower()
# Return whether a path is absolute.
# Trivial in Posix, harder on the Mac or MS-DOS.
# For DOS it is absolute if it starts with a slash or backslash (current
# volume), or if a pathname after the volume letter and colon / UNC resource
# starts with a slash or backslash.
"""Test whether a path is absolute"""
return s
!= '' and s
[:1] in '/\\'
# Join two (or more) paths.
"""Join two or more pathname components, inserting "\\" as needed"""
b_wins
= 0 # set to 1 iff b makes path irrelevant
# This probably wipes out path so far. However, it's more
# complicated if path begins with a drive letter:
# 1. join('c:', '/a') == 'c:/a'
# 2. join('c:/', '/a') == 'c:/a'
# 3. join('c:/a', '/b') == '/b'
# 4. join('c:', 'd:/') = 'd:/'
# 5. join('c:/', 'd:/') = 'd:/'
if path
[1:2] != ":" or b
[1:2] == ":":
# Path doesn't start with a drive letter, or cases 4 and 5.
# Else path has a drive letter, and b doesn't but is absolute.
elif len(path
) > 3 or (len(path
) == 3 and
# Join, and ensure there's a separator.
# path is not empty and does not end with a backslash,
# but b is empty; since, e.g., split('a/') produces
# ('a', ''), it's best if join() adds a backslash in
# Split a path in a drive specification (a drive letter followed by a
# colon) and the path specification.
# It is always true that drivespec + pathspec == p
"""Split a pathname into drive and path specifiers. Returns a 2-tuple
"(drive,path)"; either part may be empty"""
"""Split a pathname into UNC mount point and relative path specifiers.
Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.
return '', p
# Drive letter present
if firstTwo
== '//' or firstTwo
== '\\\\':
# vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
# \\machine\mountpoint\directories...
# directory ^^^^^^^^^^^^^^^
index
= normp
.find('\\', 2)
##raise RuntimeError, 'illegal UNC path: "' + p + '"'
index
= normp
.find('\\', index
+ 1)
return p
[:index
], p
[index
:]
# Split a path in head (everything up to the last '/') and tail (the
# rest). After the trailing '/' is stripped, the invariant
# join(head, tail) == p holds.
# The resulting head won't end in '/' unless it is the root.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty."""
# set i to index beyond p's last slash
while i
and p
[i
-1] not in '/\\':
head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
# remove trailing slashes from head, unless it's all slashes
while head2
and head2
[-1] in '/\\':
# Split a path in root and extension.
# The extension is everything starting at the last dot in the last
# pathname component; the root is everything before that.
# It is always true that root + ext == p.
"""Split the extension from a pathname.
Extension is everything from the last dot to the end.
Return (root, ext), either part may be empty."""
if i
<=max(p
.rfind('/'), p
.rfind('\\')):
# Return the tail (basename) part of a path.
"""Returns the final component of a pathname"""
# Return the head (dirname) part of a path.
"""Returns the directory component of a pathname"""
# Return the longest prefix of all list elements.
"Given a list of pathnames, returns the longest common leading component"
for i
in range(len(prefix
)):
if prefix
[:i
+1] != item
[:i
+1]:
# Get size, mtime, atime of files.
"""Return the size of a file, reported by os.stat()"""
return os
.stat(filename
).st_size
"""Return the last modification time of a file, reported by os.stat()"""
return os
.stat(filename
).st_mtime
"""Return the last access time of a file, reported by os.stat()"""
return os
.stat(filename
).st_atime
"""Return the creation time of a file, reported by os.stat()."""
return os
.stat(filename
).st_ctime
# Is a path a symbolic link?
# This will always return false on systems where posix.lstat doesn't exist.
"""Test for symbolic link. On WindowsNT/95 always returns false"""
"""Test whether a path exists"""
# Is a path a dos directory?
# This follows symbolic links, so both islink() and isdir() can be true
"""Test whether a path is a directory"""
return stat
.S_ISDIR(st
.st_mode
)
# Is a path a regular file?
# This follows symbolic links, so both islink() and isdir() can be true
"""Test whether a path is a regular file"""
return stat
.S_ISREG(st
.st_mode
)
# Is a path a mount point? Either a root (with or without drive letter)
# or an UNC path with at most a / or \ after the mount point.
"""Test whether a path is a mount point (defined as root of drive)"""
unc
, rest
= splitunc(path
)
return rest
in ("", "/", "\\")
return len(p
) == 1 and p
[0] in '/\\'
# For each directory under top (including top itself, but excluding
# '.' and '..'), func(arg, dirname, filenames) is called, where
# dirname is the name of the directory and filenames is the list
# of files (and subdirectories etc.) in the directory.
# The func may modify the filenames list, to implement a filter,
# or to impose a different order of visiting.
def walk(top
, func
, arg
):
"""Directory tree walk with callback function.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
dirname is the name of the directory, and fnames a list of the names of
the files and subdirectories in dirname (excluding '.' and '..'). func
may modify the fnames list in-place (e.g. via del or slice assignment),
and walk will only recurse into the subdirectories whose names remain in
fnames; this can be used to implement a filter, or to impose a specific
order of visiting. No semantics are defined for, or required of, arg,
beyond that arg is always passed to func. It can be used, e.g., to pass
a filename pattern, or a mutable object designed to accumulate
statistics. Passing None for arg is common."""
if name
not in exceptions
:
# Expand paths beginning with '~' or '~user'.
# '~' means $HOME; '~user' means that user's home directory.
# If the path doesn't begin with '~', or if the user or $HOME is unknown,
# the path is returned unchanged (leaving error reporting to whatever
# function is called with the expanded path as argument).
# See also module 'glob' for expansion of *, ? and [...] in pathnames.
# (A function should also be defined to do full *sh-style environment
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
while i
< n
and path
[i
] not in '/\\':
userhome
= os
.environ
['HOME']
elif not 'HOMEPATH' in os
.environ
:
drive
= os
.environ
['HOMEDRIVE']
userhome
= join(drive
, os
.environ
['HOMEPATH'])
return userhome
+ path
[i
:]
# Expand paths containing shell variable substitutions.
# The following rules apply:
# - no expansion within single quotes
# - no escape character, except for '$$' which is translated into '$'
# - ${varname} is accepted.
# - varnames can be made out of letters, digits and the character '_'
# XXX With COMMAND.COM you can use any characters in a variable name,
"""Expand shell variables of form $var and ${var}.
Unknown variables are left unchanged."""
varchars
= string
.ascii_letters
+ string
.digits
+ '_-'
if c
== '\'': # no expansion within single quotes
res
= res
+ '\'' + path
[:index
+ 1]
elif c
== '$': # variable or '$$'
if path
[index
+ 1:index
+ 2] == '$':
elif path
[index
+ 1:index
+ 2] == '{':
res
= res
+ os
.environ
[var
]
c
= path
[index
:index
+ 1]
while c
!= '' and c
in varchars
:
c
= path
[index
:index
+ 1]
res
= res
+ os
.environ
[var
]
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
# Previously, this function also truncated pathnames to 8+3 format,
# but as this module is called "ntpath", that's obviously wrong!
"""Normalize path, eliminating double slashes, etc."""
path
= path
.replace("/", "\\")
prefix
, path
= splitdrive(path
)
# We need to be careful here. If the prefix is empty, and the path starts
# with a backslash, it could either be an absolute path on the current
# drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It
# is therefore imperative NOT to collapse multiple backslashes blindly in
# The code below preserves multiple backslashes when there is no drive
# letter. This means that the invalid filename \\\a\b is preserved
# unchanged, where a\\\b is normalised to a\b. It's not clear that there
# is any better behaviour for such edge cases.
# No drive letter - preserve initial backslashes
# We have a drive letter - collapse initial backslashes
if path
.startswith("\\"):
if comps
[i
] in ('.', ''):
if i
> 0 and comps
[i
-1] != '..':
elif i
== 0 and prefix
.endswith("\\"):
# If the path is now empty, substitute '.'
if not prefix
and not comps
:
return prefix
+ "\\".join(comps
)
# Return an absolute path.
"""Return the absolute version of a path"""
from nt
import _getfullpathname
except ImportError: # Not running on Windows - mock up something sensible.
path
= join(os
.getcwd(), path
)
if path
: # Empty path must return current working directory.
path
= _getfullpathname(path
)
pass # Bad path - return unchanged.
# realpath is a no-op on systems without islink support
# Win9x family and earlier have no Unicode filename support.
supports_unicode_filenames
= (hasattr(sys
, "getwindowsversion") and
sys
.getwindowsversion()[3] >= 2)