blob: d8da4efa4731f5350e928cea118de76599facfab [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
16
Guido van Rossum7ac48781992-01-14 18:29:32 +000017# 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).
21
22def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000023 """Normalize case of pathname. Has no effect under Posix"""
24 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000025
26
Jeremy Hyltona05e2932000-06-28 14:48:01 +000027# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000028# Trivial in Posix, harder on the Mac or MS-DOS.
29
30def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000031 """Test whether a path is absolute"""
32 return s[:1] == '/'
Guido van Rossum7ac48781992-01-14 18:29:32 +000033
34
Barry Warsaw384d2491997-02-18 21:53:25 +000035# Join pathnames.
36# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000037# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000038
Barry Warsaw384d2491997-02-18 21:53:25 +000039def join(a, *p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000040 """Join two or more pathname components, inserting '/' as needed"""
41 path = a
42 for b in p:
43 if b[:1] == '/':
44 path = b
45 elif path == '' or path[-1:] == '/':
46 path = path + b
47 else:
48 path = path + '/' + b
49 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000050
51
Guido van Rossum26847381992-03-31 18:54:35 +000052# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000053# 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.
Guido van Rossum7ac48781992-01-14 18:29:32 +000056
Guido van Rossumc6360141990-10-13 19:23:40 +000057def split(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000058 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
59everything after the final slash. Either part may be empty"""
60 import string
61 i = string.rfind(p, '/') + 1
62 head, tail = p[:i], p[i:]
63 if head and head <> '/'*len(head):
64 while head[-1] == '/':
65 head = head[:-1]
66 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000067
68
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000069# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000070# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000071# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000072# It is always true that root + ext == p.
73
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000074def splitext(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000075 """Split the extension from a pathname. Extension is everything from the
76last dot to the end. Returns "(root, ext)", either part may be empty"""
77 root, ext = '', ''
78 for c in p:
79 if c == '/':
80 root, ext = root + ext + c, ''
81 elif c == '.':
82 if ext:
83 root, ext = root + ext, c
84 else:
85 ext = c
86 elif ext:
87 ext = ext + c
88 else:
89 root = root + c
90 return root, ext
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000091
92
Guido van Rossum221df241995-08-07 20:17:55 +000093# Split a pathname into a drive specification and the rest of the
94# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
95
96def splitdrive(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +000097 """Split a pathname into drive and path. On Posix, drive is always
98empty"""
99 return '', p
Guido van Rossum221df241995-08-07 20:17:55 +0000100
101
Guido van Rossumc6360141990-10-13 19:23:40 +0000102# Return the tail (basename) part of a path.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000103
Guido van Rossumc6360141990-10-13 19:23:40 +0000104def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000105 """Returns the final component of a pathname"""
106 return split(p)[1]
Guido van Rossumc6360141990-10-13 19:23:40 +0000107
108
Guido van Rossumc629d341992-11-05 10:43:02 +0000109# Return the head (dirname) part of a path.
110
111def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000112 """Returns the directory component of a pathname"""
113 return split(p)[0]
Guido van Rossumc629d341992-11-05 10:43:02 +0000114
115
Guido van Rossumc6360141990-10-13 19:23:40 +0000116# Return the longest prefix of all list elements.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000117
Guido van Rossumc6360141990-10-13 19:23:40 +0000118def commonprefix(m):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000119 "Given a list of pathnames, returns the longest common leading component"
120 if not m: return ''
Skip Montanaro97bc98a2000-07-12 16:55:57 +0000121 n = m[:]
122 for i in range(len(n)):
Skip Montanaroa924bb12000-07-16 16:52:45 +0000123 n[i] = n[i].split("/")
124
Skip Montanaro97bc98a2000-07-12 16:55:57 +0000125 prefix = n[0]
126 for item in n:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000127 for i in range(len(prefix)):
128 if prefix[:i+1] <> item[:i+1]:
129 prefix = prefix[:i]
130 if i == 0: return ''
131 break
Skip Montanaroa924bb12000-07-16 16:52:45 +0000132 return "/".join(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()."""
139 st = os.stat(filename)
140 return st[stat.ST_SIZE]
141
142def getmtime(filename):
143 """Return the last modification time of a file, reported by os.stat()."""
144 st = os.stat(filename)
145 return st[stat.ST_MTIME]
146
147def getatime(filename):
148 """Return the last access time of a file, reported by os.stat()."""
149 st = os.stat(filename)
Guido van Rossum98118612000-02-24 02:26:51 +0000150 return st[stat.ST_ATIME]
Guido van Rossum2bc1f8f1998-07-24 20:49:26 +0000151
152
Guido van Rossum7ac48781992-01-14 18:29:32 +0000153# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000154# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000155
156def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000157 """Test whether a path is a symbolic link"""
158 try:
159 st = os.lstat(path)
160 except (os.error, AttributeError):
161 return 0
162 return stat.S_ISLNK(st[stat.ST_MODE])
Guido van Rossum7ac48781992-01-14 18:29:32 +0000163
164
165# Does a path exist?
166# This is false for dangling symbolic links.
167
Guido van Rossumc6360141990-10-13 19:23:40 +0000168def exists(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000169 """Test whether a path exists. Returns false for broken symbolic links"""
170 try:
171 st = os.stat(path)
172 except os.error:
173 return 0
174 return 1
Guido van Rossumc6360141990-10-13 19:23:40 +0000175
176
Guido van Rossumd3876d31996-07-23 03:47:28 +0000177# Is a path a directory?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000178# This follows symbolic links, so both islink() and isdir() can be true
179# for the same path.
180
Guido van Rossumc6360141990-10-13 19:23:40 +0000181def isdir(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000182 """Test whether a path is a directory"""
183 try:
184 st = os.stat(path)
185 except os.error:
186 return 0
187 return stat.S_ISDIR(st[stat.ST_MODE])
Guido van Rossumc6360141990-10-13 19:23:40 +0000188
189
Guido van Rossum26847381992-03-31 18:54:35 +0000190# Is a path a regular file?
Guido van Rossumb6775db1994-08-01 11:34:53 +0000191# This follows symbolic links, so both islink() and isfile() can be true
Guido van Rossum7ac48781992-01-14 18:29:32 +0000192# for the same path.
193
194def isfile(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000195 """Test whether a path is a regular file"""
196 try:
197 st = os.stat(path)
198 except os.error:
199 return 0
200 return stat.S_ISREG(st[stat.ST_MODE])
Guido van Rossumc6360141990-10-13 19:23:40 +0000201
202
Guido van Rossumd3778f91991-11-12 15:37:40 +0000203# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000204
Guido van Rossumd3778f91991-11-12 15:37:40 +0000205def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000206 """Test whether two pathnames reference the same actual file"""
207 s1 = os.stat(f1)
208 s2 = os.stat(f2)
209 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000210
211
212# Are two open files really referencing the same file?
213# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000214
Guido van Rossumd3778f91991-11-12 15:37:40 +0000215def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000216 """Test whether two open file objects reference the same file"""
217 s1 = os.fstat(fp1)
218 s2 = os.fstat(fp2)
219 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000220
221
222# Are two stat buffers (obtained from stat, fstat or lstat)
223# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000224
Guido van Rossumd3778f91991-11-12 15:37:40 +0000225def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000226 """Test whether two stat buffers reference the same file"""
227 return s1[stat.ST_INO] == s2[stat.ST_INO] and \
228 s1[stat.ST_DEV] == s2[stat.ST_DEV]
Guido van Rossumc6360141990-10-13 19:23:40 +0000229
230
231# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000232# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000233
Guido van Rossumc6360141990-10-13 19:23:40 +0000234def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000235 """Test whether a path is a mount point"""
236 try:
237 s1 = os.stat(path)
238 s2 = os.stat(join(path, '..'))
239 except os.error:
240 return 0 # It doesn't exist -- so not a mount point :-)
241 dev1 = s1[stat.ST_DEV]
242 dev2 = s2[stat.ST_DEV]
243 if dev1 != dev2:
244 return 1 # path/.. on a different device as path
245 ino1 = s1[stat.ST_INO]
246 ino2 = s2[stat.ST_INO]
247 if ino1 == ino2:
248 return 1 # path/.. is the same i-node as path
249 return 0
Guido van Rossumc6360141990-10-13 19:23:40 +0000250
251
252# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000253# For each directory under top (including top itself, but excluding
254# '.' and '..'), func(arg, dirname, filenames) is called, where
255# dirname is the name of the directory and filenames is the list
Guido van Rossum346f7af1997-12-05 19:04:51 +0000256# of files (and subdirectories etc.) in the directory.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000257# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000258# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000259
Guido van Rossumc6360141990-10-13 19:23:40 +0000260def walk(top, func, arg):
Guido van Rossumf618a481999-11-02 13:29:08 +0000261 """walk(top,func,arg) calls func(arg, d, files) for each directory "d"
Guido van Rossum346f7af1997-12-05 19:04:51 +0000262in the tree rooted at "top" (including "top" itself). "files" is a list
263of all the files and subdirs in directory "d".
264"""
265 try:
266 names = os.listdir(top)
267 except os.error:
268 return
269 func(arg, top, names)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000270 for name in names:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000271 name = join(top, name)
Guido van Rossum84a74592000-02-28 14:27:07 +0000272 st = os.lstat(name)
273 if stat.S_ISDIR(st[stat.ST_MODE]):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000274 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000275
276
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.)
285
286def expanduser(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000287 """Expand ~ and ~user constructions. If user or $HOME is unknown,
288do nothing"""
289 if path[:1] <> '~':
290 return path
291 i, n = 1, len(path)
292 while i < n and path[i] <> '/':
293 i = i+1
294 if i == 1:
295 if not os.environ.has_key('HOME'):
296 return path
297 userhome = os.environ['HOME']
298 else:
299 import pwd
300 try:
301 pwent = pwd.getpwnam(path[1:i])
302 except KeyError:
303 return path
304 userhome = pwent[5]
305 if userhome[-1:] == '/': i = i+1
306 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000307
308
309# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000310# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000311# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000312
313_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000314
315def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000316 """Expand shell variables of form $var and ${var}. Unknown variables
317are left unchanged"""
318 global _varprog
319 if '$' not in path:
320 return path
321 if not _varprog:
322 import re
323 _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
324 i = 0
325 while 1:
326 m = _varprog.search(path, i)
327 if not m:
328 break
329 i, j = m.span(0)
330 name = m.group(1)
331 if name[:1] == '{' and name[-1:] == '}':
332 name = name[1:-1]
333 if os.environ.has_key(name):
334 tail = path[j:]
335 path = path[:i] + os.environ[name]
336 i = len(path)
337 path = path + tail
338 else:
339 i = j
340 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000341
342
343# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
344# It should be understood that this may change the meaning of the path
345# if it contains symbolic links!
346
347def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000348 """Normalize path, eliminating double slashes, etc."""
Skip Montanaro018dfae2000-07-19 17:09:51 +0000349 if path == '':
350 return '.'
Guido van Rossum346f7af1997-12-05 19:04:51 +0000351 import string
Skip Montanaro018dfae2000-07-19 17:09:51 +0000352 initial_slash = (path[0] == '/')
353 comps = string.split(path, '/')
354 new_comps = []
355 for comp in comps:
356 if comp in ('', '.'):
357 continue
358 if (comp != '..' or (not initial_slash and not new_comps) or
359 (new_comps and new_comps[-1] == '..')):
360 new_comps.append(comp)
361 elif new_comps:
362 new_comps.pop()
363 comps = new_comps
364 path = string.join(comps, '/')
365 if initial_slash:
366 path = '/' + path
367 return path or '.'
Guido van Rossume294cf61999-01-29 18:05:18 +0000368
369
Guido van Rossume294cf61999-01-29 18:05:18 +0000370def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000371 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000372 if not isabs(path):
373 path = join(os.getcwd(), path)
374 return normpath(path)