blob: 6c66689b6b1d96eba9f853f76bccdef6c466c0c7 [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Common operations on Posix pathnames.
2
3Instead of importing this module directly, import os and refer to
4this module as os.path. The "os.path" name is an alias for this
5module on Posix systems; on other systems (e.g. Mac, Windows),
6os.path provides the same operations in a manner specific to that
7platform, and is an alias to another module (e.g. macpath, ntpath).
8
9Some of this can actually be useful on non-Posix systems too, e.g.
10for manipulation of the pathname component of URLs.
Guido van Rossum346f7af1997-12-05 19:04:51 +000011"""
Guido van Rossumc6360141990-10-13 19:23:40 +000012
Guido van Rossumd3876d31996-07-23 03:47:28 +000013import os
Guido van Rossum40d93041990-10-21 16:17:34 +000014import stat
Guido van Rossumc6360141990-10-13 19:23:40 +000015
Skip Montanaroc62c81e2001-02-12 02:00:42 +000016__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
17 "basename","dirname","commonprefix","getsize","getmtime",
18 "getatime","islink","exists","isdir","isfile","ismount",
19 "walk","expanduser","expandvars","normpath","abspath",
20 "samefile","sameopenfile","samestat"]
Guido van Rossumc6360141990-10-13 19:23:40 +000021
Guido van Rossum7ac48781992-01-14 18:29:32 +000022# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
23# On MS-DOS this may also turn slashes into backslashes; however, other
24# normalizations (such as optimizing '../' away) are not allowed
25# (another function should be defined to do that).
26
27def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000028 """Normalize case of pathname. Has no effect under Posix"""
29 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000030
31
Jeremy Hyltona05e2932000-06-28 14:48:01 +000032# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000033# Trivial in Posix, harder on the Mac or MS-DOS.
34
35def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000036 """Test whether a path is absolute"""
37 return s[:1] == '/'
Guido van Rossum7ac48781992-01-14 18:29:32 +000038
39
Barry Warsaw384d2491997-02-18 21:53:25 +000040# Join pathnames.
41# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000042# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000043
Barry Warsaw384d2491997-02-18 21:53:25 +000044def join(a, *p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000045 """Join two or more pathname components, inserting '/' as needed"""
46 path = a
47 for b in p:
48 if b[:1] == '/':
49 path = b
50 elif path == '' or path[-1:] == '/':
51 path = path + b
52 else:
53 path = path + '/' + b
54 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000055
56
Guido van Rossum26847381992-03-31 18:54:35 +000057# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000058# rest). If the path ends in '/', tail will be empty. If there is no
59# '/' in the path, head will be empty.
60# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000061
Guido van Rossumc6360141990-10-13 19:23:40 +000062def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000063 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000064 everything after the final slash. Either part may be empty."""
Fred Drake22fb8392000-09-28 15:04:39 +000065 i = p.rfind('/') + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +000066 head, tail = p[:i], p[i:]
Fred Drake8152d322000-12-12 23:20:45 +000067 if head and head != '/'*len(head):
Guido van Rossum346f7af1997-12-05 19:04:51 +000068 while head[-1] == '/':
69 head = head[:-1]
70 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000071
72
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000073# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000074# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000075# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000076# It is always true that root + ext == p.
77
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000078def splitext(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000079 """Split the extension from a pathname. Extension is everything from the
Fred Drakec0ab93e2000-09-28 16:22:52 +000080 last dot to the end. Returns "(root, ext)", either part may be empty."""
Guido van Rossum346f7af1997-12-05 19:04:51 +000081 root, ext = '', ''
82 for c in p:
83 if c == '/':
84 root, ext = root + ext + c, ''
85 elif c == '.':
86 if ext:
87 root, ext = root + ext, c
88 else:
89 ext = c
90 elif ext:
91 ext = ext + c
92 else:
93 root = root + c
94 return root, ext
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000095
96
Guido van Rossum221df241995-08-07 20:17:55 +000097# Split a pathname into a drive specification and the rest of the
98# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
99
100def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000101 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000102 empty."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000103 return '', p
Guido van Rossum221df241995-08-07 20:17:55 +0000104
105
Guido van Rossumc6360141990-10-13 19:23:40 +0000106# Return the tail (basename) part of a path.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000107
Guido van Rossumc6360141990-10-13 19:23:40 +0000108def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000109 """Returns the final component of a pathname"""
110 return split(p)[1]
Guido van Rossumc6360141990-10-13 19:23:40 +0000111
112
Guido van Rossumc629d341992-11-05 10:43:02 +0000113# Return the head (dirname) part of a path.
114
115def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000116 """Returns the directory component of a pathname"""
117 return split(p)[0]
Guido van Rossumc629d341992-11-05 10:43:02 +0000118
119
Guido van Rossumc6360141990-10-13 19:23:40 +0000120# Return the longest prefix of all list elements.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000121
Guido van Rossumc6360141990-10-13 19:23:40 +0000122def commonprefix(m):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000123 "Given a list of pathnames, returns the longest common leading component"
124 if not m: return ''
Skip Montanaro62358312000-08-22 13:01:53 +0000125 prefix = m[0]
126 for item in m:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000127 for i in range(len(prefix)):
Fred Drake8152d322000-12-12 23:20:45 +0000128 if prefix[:i+1] != item[:i+1]:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000129 prefix = prefix[:i]
130 if i == 0: return ''
131 break
Skip Montanaro62358312000-08-22 13:01:53 +0000132 return prefix
Guido van Rossumc6360141990-10-13 19:23:40 +0000133
134
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000135# Get size, mtime, atime of files.
136
137def getsize(filename):
138 """Return the size of a file, reported by os.stat()."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000139 return os.stat(filename).st_size
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000140
141def getmtime(filename):
142 """Return the last modification time of a file, reported by os.stat()."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000143 return os.stat(filename).st_mtime
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000144
145def getatime(filename):
146 """Return the last access time of a file, reported by os.stat()."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000147 return os.stat(filename).st_atime
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000148
149
Guido van Rossum7ac48781992-01-14 18:29:32 +0000150# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000151# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000152
153def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000154 """Test whether a path is a symbolic link"""
155 try:
156 st = os.lstat(path)
157 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000158 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000159 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000160
161
162# Does a path exist?
163# This is false for dangling symbolic links.
164
Guido van Rossumc6360141990-10-13 19:23:40 +0000165def exists(path):
Tim Petersbc0e9102002-04-04 22:55:58 +0000166 """Test whether a path exists. Returns False for broken symbolic links"""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000167 try:
168 st = os.stat(path)
169 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000170 return False
171 return True
Guido van Rossumc6360141990-10-13 19:23:40 +0000172
173
Guido van Rossumd3876d31996-07-23 03:47:28 +0000174# Is a path a directory?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000175# This follows symbolic links, so both islink() and isdir() can be true
176# for the same path.
177
Guido van Rossumc6360141990-10-13 19:23:40 +0000178def isdir(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000179 """Test whether a path is a directory"""
180 try:
181 st = os.stat(path)
182 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000183 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000184 return stat.S_ISDIR(st.st_mode)
Guido van Rossumc6360141990-10-13 19:23:40 +0000185
186
Guido van Rossum26847381992-03-31 18:54:35 +0000187# Is a path a regular file?
Guido van Rossumb6775db1994-08-01 11:34:53 +0000188# This follows symbolic links, so both islink() and isfile() can be true
Guido van Rossum7ac48781992-01-14 18:29:32 +0000189# for the same path.
190
191def isfile(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000192 """Test whether a path is a regular file"""
193 try:
194 st = os.stat(path)
195 except os.error:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000196 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000197 return stat.S_ISREG(st.st_mode)
Guido van Rossumc6360141990-10-13 19:23:40 +0000198
199
Guido van Rossumd3778f91991-11-12 15:37:40 +0000200# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000201
Guido van Rossumd3778f91991-11-12 15:37:40 +0000202def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000203 """Test whether two pathnames reference the same actual file"""
204 s1 = os.stat(f1)
205 s2 = os.stat(f2)
206 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000207
208
209# Are two open files really referencing the same file?
210# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000211
Guido van Rossumd3778f91991-11-12 15:37:40 +0000212def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000213 """Test whether two open file objects reference the same file"""
214 s1 = os.fstat(fp1)
215 s2 = os.fstat(fp2)
216 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000217
218
219# Are two stat buffers (obtained from stat, fstat or lstat)
220# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000221
Guido van Rossumd3778f91991-11-12 15:37:40 +0000222def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000223 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000224 return s1.st_ino == s2.st_ino and \
225 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000226
227
228# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000229# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000230
Guido van Rossumc6360141990-10-13 19:23:40 +0000231def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000232 """Test whether a path is a mount point"""
233 try:
234 s1 = os.stat(path)
235 s2 = os.stat(join(path, '..'))
236 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000237 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000238 dev1 = s1.st_dev
239 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000240 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000241 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000242 ino1 = s1.st_ino
243 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000244 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000245 return True # path/.. is the same i-node as path
246 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000247
248
249# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000250# For each directory under top (including top itself, but excluding
251# '.' and '..'), func(arg, dirname, filenames) is called, where
252# dirname is the name of the directory and filenames is the list
Guido van Rossum346f7af1997-12-05 19:04:51 +0000253# of files (and subdirectories etc.) in the directory.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000254# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000255# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000256
Guido van Rossumc6360141990-10-13 19:23:40 +0000257def walk(top, func, arg):
Tim Peterscf5e6a42001-10-10 04:16:20 +0000258 """Directory tree walk with callback function.
259
260 For each directory in the directory tree rooted at top (including top
261 itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
262 dirname is the name of the directory, and fnames a list of the names of
263 the files and subdirectories in dirname (excluding '.' and '..'). func
264 may modify the fnames list in-place (e.g. via del or slice assignment),
265 and walk will only recurse into the subdirectories whose names remain in
266 fnames; this can be used to implement a filter, or to impose a specific
267 order of visiting. No semantics are defined for, or required of, arg,
268 beyond that arg is always passed to func. It can be used, e.g., to pass
269 a filename pattern, or a mutable object designed to accumulate
270 statistics. Passing None for arg is common."""
271
Guido van Rossum346f7af1997-12-05 19:04:51 +0000272 try:
273 names = os.listdir(top)
274 except os.error:
275 return
276 func(arg, top, names)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000277 for name in names:
Tim Peters2344fae2001-01-15 00:50:52 +0000278 name = join(top, name)
Guido van Rossuma490d582001-04-16 18:12:04 +0000279 try:
280 st = os.lstat(name)
281 except os.error:
282 continue
Neal Norwitzec7cf132002-06-06 18:16:14 +0000283 if stat.S_ISDIR(st.st_mode):
Tim Peters2344fae2001-01-15 00:50:52 +0000284 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000285
286
287# Expand paths beginning with '~' or '~user'.
288# '~' means $HOME; '~user' means that user's home directory.
289# If the path doesn't begin with '~', or if the user or $HOME is unknown,
290# the path is returned unchanged (leaving error reporting to whatever
291# function is called with the expanded path as argument).
292# See also module 'glob' for expansion of *, ? and [...] in pathnames.
293# (A function should also be defined to do full *sh-style environment
294# variable expansion.)
295
296def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000297 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000298 do nothing."""
Fred Drake8152d322000-12-12 23:20:45 +0000299 if path[:1] != '~':
Guido van Rossum346f7af1997-12-05 19:04:51 +0000300 return path
301 i, n = 1, len(path)
Fred Drake8152d322000-12-12 23:20:45 +0000302 while i < n and path[i] != '/':
Fred Drakec0ab93e2000-09-28 16:22:52 +0000303 i = i + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000304 if i == 1:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000305 if not 'HOME' in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000306 return path
307 userhome = os.environ['HOME']
308 else:
309 import pwd
310 try:
311 pwent = pwd.getpwnam(path[1:i])
312 except KeyError:
313 return path
314 userhome = pwent[5]
Fred Drakec0ab93e2000-09-28 16:22:52 +0000315 if userhome[-1:] == '/': i = i + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000316 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000317
318
319# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000320# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000321# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000322
323_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000324
325def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000326 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000327 are left unchanged."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000328 global _varprog
329 if '$' not in path:
330 return path
331 if not _varprog:
332 import re
333 _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
334 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000335 while True:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000336 m = _varprog.search(path, i)
337 if not m:
338 break
339 i, j = m.span(0)
340 name = m.group(1)
341 if name[:1] == '{' and name[-1:] == '}':
342 name = name[1:-1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000343 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000344 tail = path[j:]
345 path = path[:i] + os.environ[name]
346 i = len(path)
347 path = path + tail
348 else:
349 i = j
350 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000351
352
353# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
354# It should be understood that this may change the meaning of the path
355# if it contains symbolic links!
356
357def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000358 """Normalize path, eliminating double slashes, etc."""
Skip Montanaro018dfae2000-07-19 17:09:51 +0000359 if path == '':
360 return '.'
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000361 initial_slashes = path.startswith('/')
362 # POSIX allows one or two initial slashes, but treats three or more
363 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000364 if (initial_slashes and
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000365 path.startswith('//') and not path.startswith('///')):
366 initial_slashes = 2
Fred Drake22fb8392000-09-28 15:04:39 +0000367 comps = path.split('/')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000368 new_comps = []
369 for comp in comps:
370 if comp in ('', '.'):
371 continue
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000372 if (comp != '..' or (not initial_slashes and not new_comps) or
Skip Montanaro018dfae2000-07-19 17:09:51 +0000373 (new_comps and new_comps[-1] == '..')):
374 new_comps.append(comp)
375 elif new_comps:
376 new_comps.pop()
377 comps = new_comps
Fred Drake22fb8392000-09-28 15:04:39 +0000378 path = '/'.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000379 if initial_slashes:
380 path = '/'*initial_slashes + path
Skip Montanaro018dfae2000-07-19 17:09:51 +0000381 return path or '.'
Guido van Rossume294cf61999-01-29 18:05:18 +0000382
383
Guido van Rossume294cf61999-01-29 18:05:18 +0000384def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000385 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000386 if not isabs(path):
387 path = join(os.getcwd(), path)
388 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000389
390
391# Return a canonical path (i.e. the absolute location of a file on the
392# filesystem).
393
394def realpath(filename):
395 """Return the canonical path of the specified filename, eliminating any
396symbolic links encountered in the path."""
397 filename = abspath(filename)
398
399 bits = ['/'] + filename.split('/')[1:]
400 for i in range(2, len(bits)+1):
401 component = join(*bits[0:i])
402 if islink(component):
403 resolved = os.readlink(component)
404 (dir, file) = split(component)
405 resolved = normpath(join(dir, resolved))
406 newpath = join(*([resolved] + bits[i:]))
407 return realpath(newpath)
Tim Petersb64bec32001-09-18 02:26:39 +0000408
Guido van Rossum83eeef42001-09-17 15:16:09 +0000409 return filename