1 """Common operations on Posix pathnames.
3 Instead of importing this module directly, import os and refer to
4 this module as os.path. The "os.path" name is an alias for this
5 module on Posix systems; on other systems (e.g. Mac, Windows),
6 os.path provides the same operations in a manner specific to that
7 platform, and is an alias to another module (e.g. macpath, ntpath).
9 Some of this can actually be useful on non-Posix systems too, e.g.
10 for manipulation of the pathname component of URLs.
17 # Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
18 # On MS-DOS this may also turn slashes into backslashes; however, other
19 # normalizations (such as optimizing '../' away) are not allowed
20 # (another function should be defined to do that).
23 """Normalize case of pathname. Has no effect under Posix"""
27 # Return whether a path is absolute.
28 # Trivial in Posix, harder on the Mac or MS-DOS.
31 """Test whether a path is absolute"""
36 # Ignore the previous parts if a part is absolute.
37 # Insert a '/' unless the first part is empty or already ends in '/'.
40 """Join two or more pathname components, inserting '/' as needed"""
45 elif path
== '' or path
[-1:] == '/':
52 # Split a path in head (everything up to the last '/') and tail (the
53 # rest). If the path ends in '/', tail will be empty. If there is no
54 # '/' in the path, head will be empty.
55 # Trailing '/'es are stripped from head unless it is the root.
58 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
59 everything after the final slash. Either part may be empty."""
61 head
, tail
= p
[:i
], p
[i
:]
62 if head
and head
<> '/'*len(head
):
63 while head
[-1] == '/':
68 # Split a path in root and extension.
69 # The extension is everything starting at the last dot in the last
70 # pathname component; the root is everything before that.
71 # It is always true that root + ext == p.
74 """Split the extension from a pathname. Extension is everything from the
75 last dot to the end. Returns "(root, ext)", either part may be empty."""
79 root
, ext
= root
+ ext
+ c
, ''
82 root
, ext
= root
+ ext
, c
92 # Split a pathname into a drive specification and the rest of the
93 # path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
96 """Split a pathname into drive and path. On Posix, drive is always
101 # Return the tail (basename) part of a path.
104 """Returns the final component of a pathname"""
108 # Return the head (dirname) part of a path.
111 """Returns the directory component of a pathname"""
115 # Return the longest prefix of all list elements.
118 "Given a list of pathnames, returns the longest common leading component"
122 for i
in range(len(prefix
)):
123 if prefix
[:i
+1] <> item
[:i
+1]:
130 # Get size, mtime, atime of files.
132 def getsize(filename
):
133 """Return the size of a file, reported by os.stat()."""
134 st
= os
.stat(filename
)
135 return st
[stat
.ST_SIZE
]
137 def getmtime(filename
):
138 """Return the last modification time of a file, reported by os.stat()."""
139 st
= os
.stat(filename
)
140 return st
[stat
.ST_MTIME
]
142 def getatime(filename
):
143 """Return the last access time of a file, reported by os.stat()."""
144 st
= os
.stat(filename
)
145 return st
[stat
.ST_ATIME
]
148 # Is a path a symbolic link?
149 # This will always return false on systems where os.lstat doesn't exist.
152 """Test whether a path is a symbolic link"""
155 except (os
.error
, AttributeError):
157 return stat
.S_ISLNK(st
[stat
.ST_MODE
])
161 # This is false for dangling symbolic links.
164 """Test whether a path exists. Returns false for broken symbolic links"""
172 # Is a path a directory?
173 # This follows symbolic links, so both islink() and isdir() can be true
177 """Test whether a path is a directory"""
182 return stat
.S_ISDIR(st
[stat
.ST_MODE
])
185 # Is a path a regular file?
186 # This follows symbolic links, so both islink() and isfile() can be true
190 """Test whether a path is a regular file"""
195 return stat
.S_ISREG(st
[stat
.ST_MODE
])
198 # Are two filenames really pointing to the same file?
200 def samefile(f1
, f2
):
201 """Test whether two pathnames reference the same actual file"""
204 return samestat(s1
, s2
)
207 # Are two open files really referencing the same file?
208 # (Not necessarily the same file descriptor!)
210 def sameopenfile(fp1
, fp2
):
211 """Test whether two open file objects reference the same file"""
214 return samestat(s1
, s2
)
217 # Are two stat buffers (obtained from stat, fstat or lstat)
218 # describing the same file?
220 def samestat(s1
, s2
):
221 """Test whether two stat buffers reference the same file"""
222 return s1
[stat
.ST_INO
] == s2
[stat
.ST_INO
] and \
223 s1
[stat
.ST_DEV
] == s2
[stat
.ST_DEV
]
226 # Is a path a mount point?
227 # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
230 """Test whether a path is a mount point"""
233 s2
= os
.stat(join(path
, '..'))
235 return 0 # It doesn't exist -- so not a mount point :-)
236 dev1
= s1
[stat
.ST_DEV
]
237 dev2
= s2
[stat
.ST_DEV
]
239 return 1 # path/.. on a different device as path
240 ino1
= s1
[stat
.ST_INO
]
241 ino2
= s2
[stat
.ST_INO
]
243 return 1 # path/.. is the same i-node as path
247 # Directory tree walk.
248 # For each directory under top (including top itself, but excluding
249 # '.' and '..'), func(arg, dirname, filenames) is called, where
250 # dirname is the name of the directory and filenames is the list
251 # of files (and subdirectories etc.) in the directory.
252 # The func may modify the filenames list, to implement a filter,
253 # or to impose a different order of visiting.
255 def walk(top
, func
, arg
):
256 """walk(top,func,arg) calls func(arg, d, files) for each directory "d"
257 in the tree rooted at "top" (including "top" itself). "files" is a list
258 of all the files and subdirs in directory "d".
261 names
= os
.listdir(top
)
264 func(arg
, top
, names
)
266 name
= join(top
, name
)
268 if stat
.S_ISDIR(st
[stat
.ST_MODE
]):
269 walk(name
, func
, arg
)
272 # Expand paths beginning with '~' or '~user'.
273 # '~' means $HOME; '~user' means that user's home directory.
274 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
275 # the path is returned unchanged (leaving error reporting to whatever
276 # function is called with the expanded path as argument).
277 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
278 # (A function should also be defined to do full *sh-style environment
279 # variable expansion.)
281 def expanduser(path
):
282 """Expand ~ and ~user constructions. If user or $HOME is unknown,
287 while i
< n
and path
[i
] <> '/':
290 if not os
.environ
.has_key('HOME'):
292 userhome
= os
.environ
['HOME']
296 pwent
= pwd
.getpwnam(path
[1:i
])
300 if userhome
[-1:] == '/': i
= i
+ 1
301 return userhome
+ path
[i
:]
304 # Expand paths containing shell variable substitutions.
305 # This expands the forms $variable and ${variable} only.
306 # Non-existent variables are left unchanged.
310 def expandvars(path
):
311 """Expand shell variables of form $var and ${var}. Unknown variables
312 are left unchanged."""
318 _varprog
= re
.compile(r
'\$(\w+|\{[^}]*\})')
321 m
= _varprog
.search(path
, i
)
326 if name
[:1] == '{' and name
[-1:] == '}':
328 if os
.environ
.has_key(name
):
330 path
= path
[:i
] + os
.environ
[name
]
338 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
339 # It should be understood that this may change the meaning of the path
340 # if it contains symbolic links!
343 """Normalize path, eliminating double slashes, etc."""
346 initial_slash
= (path
[0] == '/')
347 comps
= path
.split('/')
350 if comp
in ('', '.'):
352 if (comp
!= '..' or (not initial_slash
and not new_comps
) or
353 (new_comps
and new_comps
[-1] == '..')):
354 new_comps
.append(comp
)
358 path
= '/'.join(comps
)
365 """Return an absolute path."""
367 path
= join(os
.getcwd(), path
)
368 return normpath(path
)