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"""
47 elif path
== '' or path
[-1:] in '/\\:':
50 path
= path
+ "\\" + b
54 # Split a path in a drive specification (a drive letter followed by a
55 # colon) and the path specification.
56 # It is always true that drivespec + pathspec == p
58 """Split a pathname into drive and path specifiers. Returns a 2-tuple
59 "(drive,path)"; either part may be empty"""
67 """Split a pathname into UNC mount point and relative path specifiers.
69 Return a 2-tuple (unc, rest); either part may be empty.
70 If unc is not empty, it has the form '//host/mount' (or similar
71 using backslashes). unc+rest is always the input path.
72 Paths containing drive letters never have an UNC part.
75 return '', p
# Drive letter present
77 if firstTwo
== '//' or firstTwo
== '\\\\':
79 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
80 # \\machine\mountpoint\directories...
81 # directory ^^^^^^^^^^^^^^^
83 index
= normp
.find('\\', 2)
85 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
87 index
= normp
.find('\\', index
+ 1)
90 return p
[:index
], p
[index
:]
94 # Split a path in head (everything up to the last '/') and tail (the
95 # rest). After the trailing '/' is stripped, the invariant
96 # join(head, tail) == p holds.
97 # The resulting head won't end in '/' unless it is the root.
102 Return tuple (head, tail) where tail is everything after the final slash.
103 Either part may be empty."""
106 # set i to index beyond p's last slash
108 while i
and p
[i
-1] not in '/\\':
110 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
111 # remove trailing slashes from head, unless it's all slashes
113 while head2
and head2
[-1] in '/\\':
116 return d
+ head
, tail
119 # Split a path in root and extension.
120 # The extension is everything starting at the last dot in the last
121 # pathname component; the root is everything before that.
122 # It is always true that root + ext == p.
125 """Split the extension from a pathname.
127 Extension is everything from the last dot to the end.
128 Return (root, ext), either part may be empty."""
132 root
, ext
= root
+ ext
+ c
, ''
135 root
, ext
= root
+ ext
, c
145 # Return the tail (basename) part of a path.
148 """Returns the final component of a pathname"""
152 # Return the head (dirname) part of a path.
155 """Returns the directory component of a pathname"""
159 # Return the longest prefix of all list elements.
162 "Given a list of pathnames, returns the longest common leading component"
166 for i
in range(len(prefix
)):
167 if prefix
[:i
+1] != item
[:i
+1]:
174 # Get size, mtime, atime of files.
176 def getsize(filename
):
177 """Return the size of a file, reported by os.stat()"""
178 st
= os
.stat(filename
)
179 return st
[stat
.ST_SIZE
]
181 def getmtime(filename
):
182 """Return the last modification time of a file, reported by os.stat()"""
183 st
= os
.stat(filename
)
184 return st
[stat
.ST_MTIME
]
186 def getatime(filename
):
187 """Return the last access time of a file, reported by os.stat()"""
188 st
= os
.stat(filename
)
189 return st
[stat
.ST_ATIME
]
192 # Is a path a symbolic link?
193 # This will always return false on systems where posix.lstat doesn't exist.
196 """Test for symbolic link. On WindowsNT/95 always returns false"""
201 # This is false for dangling symbolic links.
204 """Test whether a path exists"""
212 # Is a path a dos directory?
213 # This follows symbolic links, so both islink() and isdir() can be true
217 """Test whether a path is a directory"""
222 return stat
.S_ISDIR(st
[stat
.ST_MODE
])
225 # Is a path a regular file?
226 # This follows symbolic links, so both islink() and isdir() can be true
230 """Test whether a path is a regular file"""
235 return stat
.S_ISREG(st
[stat
.ST_MODE
])
238 # Is a path a mount point? Either a root (with or without drive letter)
239 # or an UNC path with at most a / or \ after the mount point.
242 """Test whether a path is a mount point (defined as root of drive)"""
243 unc
, rest
= splitunc(path
)
245 return rest
in ("", "/", "\\")
246 p
= splitdrive(path
)[1]
247 return len(p
) == 1 and p
[0] in '/\\'
250 # Directory tree walk.
251 # For each directory under top (including top itself, but excluding
252 # '.' and '..'), func(arg, dirname, filenames) is called, where
253 # dirname is the name of the directory and filenames is the list
254 # files files (and subdirectories etc.) in the directory.
255 # The func may modify the filenames list, to implement a filter,
256 # or to impose a different order of visiting.
258 def walk(top
, func
, arg
):
259 """Directory tree walk whth callback function.
261 walk(top, func, arg) calls func(arg, d, files) for each directory d
262 in the tree rooted at top (including top itself); files is a list
263 of all the files and subdirs in directory d."""
265 names
= os
.listdir(top
)
268 func(arg
, top
, names
)
269 exceptions
= ('.', '..')
271 if name
not in exceptions
:
272 name
= join(top
, name
)
274 walk(name
, func
, arg
)
277 # Expand paths beginning with '~' or '~user'.
278 # '~' means $HOME; '~user' means that user's home directory.
279 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
280 # the path is returned unchanged (leaving error reporting to whatever
281 # function is called with the expanded path as argument).
282 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
283 # (A function should also be defined to do full *sh-style environment
284 # variable expansion.)
286 def expanduser(path
):
287 """Expand ~ and ~user constructs.
289 If user or $HOME is unknown, do nothing."""
293 while i
< n
and path
[i
] not in '/\\':
296 if os
.environ
.has_key('HOME'):
297 userhome
= os
.environ
['HOME']
298 elif not os
.environ
.has_key('HOMEPATH'):
302 drive
= os
.environ
['HOMEDRIVE']
305 userhome
= join(drive
, os
.environ
['HOMEPATH'])
308 return userhome
+ path
[i
:]
311 # Expand paths containing shell variable substitutions.
312 # The following rules apply:
313 # - no expansion within single quotes
314 # - no escape character, except for '$$' which is translated into '$'
315 # - ${varname} is accepted.
316 # - varnames can be made out of letters, digits and the character '_'
317 # XXX With COMMAND.COM you can use any characters in a variable name,
318 # XXX except '^|<>='.
320 def expandvars(path
):
321 """Expand shell variables of form $var and ${var}.
323 Unknown variables are left unchanged."""
327 varchars
= string
.letters
+ string
.digits
+ '_-'
331 while index
< pathlen
:
333 if c
== '\'': # no expansion within single quotes
334 path
= path
[index
+ 1:]
337 index
= path
.index('\'')
338 res
= res
+ '\'' + path
[:index
+ 1]
342 elif c
== '$': # variable or '$$'
343 if path
[index
+ 1:index
+ 2] == '$':
346 elif path
[index
+ 1:index
+ 2] == '{':
347 path
= path
[index
+2:]
350 index
= path
.index('}')
352 if os
.environ
.has_key(var
):
353 res
= res
+ os
.environ
[var
]
360 c
= path
[index
:index
+ 1]
361 while c
!= '' and c
in varchars
:
364 c
= path
[index
:index
+ 1]
365 if os
.environ
.has_key(var
):
366 res
= res
+ os
.environ
[var
]
375 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
376 # Previously, this function also truncated pathnames to 8+3 format,
377 # but as this module is called "ntpath", that's obviously wrong!
380 """Normalize path, eliminating double slashes, etc."""
381 path
= path
.replace("/", "\\")
382 prefix
, path
= splitdrive(path
)
383 while path
[:1] == "\\":
384 prefix
= prefix
+ "\\"
386 comps
= path
.split("\\")
388 while i
< len(comps
):
391 elif comps
[i
] == '..' and i
> 0 and comps
[i
-1] not in ('', '..'):
394 elif comps
[i
] == '' and i
> 0 and comps
[i
-1] != '':
398 # If the path is now empty, substitute '.'
399 if not prefix
and not comps
:
401 return prefix
+ "\\".join(comps
)
404 # Return an absolute path.
406 """Return the absolute version of a path"""
413 path
= join(os
.getcwd(), path
)
414 return normpath(path
)
416 return _abspath(path
)
417 if path
: # Empty path must return current working directory.
419 path
= win32api
.GetFullPathName(path
)
420 except win32api
.error
:
421 pass # Bad path - return unchanged.
424 return normpath(path
)