blob: 05eed8a2b80f833e9bdf64869d21d82af91a58b5 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`os.path` --- Common pathname manipulations
3================================================
4
5.. module:: os.path
6 :synopsis: Operations on pathnames.
7
8
9.. index:: single: path; operations
10
11This module implements some useful functions on pathnames. To read or
12write files see :func:`open`, and for accessing the filesystem see the
13:mod:`os` module.
14
15.. warning::
16
17 On Windows, many of these functions do not properly support UNC pathnames.
18 :func:`splitunc` and :func:`ismount` do handle them correctly.
19
20
21.. function:: abspath(path)
22
23 Return a normalized absolutized version of the pathname *path*. On most
24 platforms, this is equivalent to ``normpath(join(os.getcwd(), path))``.
25
26 .. versionadded:: 1.5.2
27
28
29.. function:: basename(path)
30
31 Return the base name of pathname *path*. This is the second half of the pair
32 returned by ``split(path)``. Note that the result of this function is different
33 from the Unix :program:`basename` program; where :program:`basename` for
34 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
35 empty string (``''``).
36
37
38.. function:: commonprefix(list)
39
40 Return the longest path prefix (taken character-by-character) that is a prefix
41 of all paths in *list*. If *list* is empty, return the empty string (``''``).
42 Note that this may return invalid paths because it works a character at a time.
43
44
45.. function:: dirname(path)
46
47 Return the directory name of pathname *path*. This is the first half of the
48 pair returned by ``split(path)``.
49
50
51.. function:: exists(path)
52
53 Return ``True`` if *path* refers to an existing path. Returns ``False`` for
54 broken symbolic links. On some platforms, this function may return ``False`` if
55 permission is not granted to execute :func:`os.stat` on the requested file, even
56 if the *path* physically exists.
57
58
59.. function:: lexists(path)
60
61 Return ``True`` if *path* refers to an existing path. Returns ``True`` for
62 broken symbolic links. Equivalent to :func:`exists` on platforms lacking
63 :func:`os.lstat`.
64
65 .. versionadded:: 2.4
66
67
68.. function:: expanduser(path)
69
70 On Unix and Windows, return the argument with an initial component of ``~`` or
71 ``~user`` replaced by that *user*'s home directory.
72
73 .. index:: module: pwd
74
75 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
76 if it is set; otherwise the current user's home directory is looked up in the
77 password directory through the built-in module :mod:`pwd`. An initial ``~user``
78 is looked up directly in the password directory.
79
80 On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
81 otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
82 used. An initial ``~user`` is handled by stripping the last directory component
83 from the created user path derived above.
84
85 If the expansion fails or if the path does not begin with a tilde, the path is
86 returned unchanged.
87
88
89.. function:: expandvars(path)
90
91 Return the argument with environment variables expanded. Substrings of the form
92 ``$name`` or ``${name}`` are replaced by the value of environment variable
93 *name*. Malformed variable names and references to non-existing variables are
94 left unchanged.
95
96 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
97 ``${name}``.
98
99
100.. function:: getatime(path)
101
102 Return the time of last access of *path*. The return value is a number giving
103 the number of seconds since the epoch (see the :mod:`time` module). Raise
104 :exc:`os.error` if the file does not exist or is inaccessible.
105
106 .. versionadded:: 1.5.2
107
108 .. versionchanged:: 2.3
109 If :func:`os.stat_float_times` returns True, the result is a floating point
110 number.
111
112
113.. function:: getmtime(path)
114
115 Return the time of last modification of *path*. The return value is a number
116 giving the number of seconds since the epoch (see the :mod:`time` module).
117 Raise :exc:`os.error` if the file does not exist or is inaccessible.
118
119 .. versionadded:: 1.5.2
120
121 .. versionchanged:: 2.3
122 If :func:`os.stat_float_times` returns True, the result is a floating point
123 number.
124
125
126.. function:: getctime(path)
127
128 Return the system's ctime which, on some systems (like Unix) is the time of the
129 last change, and, on others (like Windows), is the creation time for *path*.
130 The return value is a number giving the number of seconds since the epoch (see
131 the :mod:`time` module). Raise :exc:`os.error` if the file does not exist or
132 is inaccessible.
133
134 .. versionadded:: 2.3
135
136
137.. function:: getsize(path)
138
139 Return the size, in bytes, of *path*. Raise :exc:`os.error` if the file does
140 not exist or is inaccessible.
141
142 .. versionadded:: 1.5.2
143
144
145.. function:: isabs(path)
146
Georg Brandlfe7dd502008-01-26 09:43:35 +0000147 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
148 begins with a slash, on Windows that it begins with a backslash after chopping
149 off a potential drive letter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151
152.. function:: isfile(path)
153
154 Return ``True`` if *path* is an existing regular file. This follows symbolic
155 links, so both :func:`islink` and :func:`isfile` can be true for the same path.
156
157
158.. function:: isdir(path)
159
160 Return ``True`` if *path* is an existing directory. This follows symbolic
161 links, so both :func:`islink` and :func:`isdir` can be true for the same path.
162
163
164.. function:: islink(path)
165
166 Return ``True`` if *path* refers to a directory entry that is a symbolic link.
167 Always ``False`` if symbolic links are not supported.
168
169
170.. function:: ismount(path)
171
172 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file
173 system where a different file system has been mounted. The function checks
174 whether *path*'s parent, :file:`path/..`, is on a different device than *path*,
175 or whether :file:`path/..` and *path* point to the same i-node on the same
176 device --- this should detect mount points for all Unix and POSIX variants.
177
178
179.. function:: join(path1[, path2[, ...]])
180
181 Join one or more path components intelligently. If any component is an absolute
182 path, all previous components (on Windows, including the previous drive letter,
183 if there was one) are thrown away, and joining continues. The return value is
184 the concatenation of *path1*, and optionally *path2*, etc., with exactly one
185 directory separator (``os.sep``) inserted between components, unless *path2* is
186 empty. Note that on Windows, since there is a current directory for each drive,
187 ``os.path.join("c:", "foo")`` represents a path relative to the current
188 directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
189
190
191.. function:: normcase(path)
192
193 Normalize the case of a pathname. On Unix, this returns the path unchanged; on
194 case-insensitive filesystems, it converts the path to lowercase. On Windows, it
195 also converts forward slashes to backward slashes.
196
197
198.. function:: normpath(path)
199
200 Normalize a pathname. This collapses redundant separators and up-level
201 references so that ``A//B``, ``A/./B`` and ``A/foo/../B`` all become ``A/B``.
202 It does not normalize the case (use :func:`normcase` for that). On Windows, it
203 converts forward slashes to backward slashes. It should be understood that this
204 may change the meaning of the path if it contains symbolic links!
205
206
207.. function:: realpath(path)
208
209 Return the canonical path of the specified filename, eliminating any symbolic
210 links encountered in the path (if they are supported by the operating system).
211
212 .. versionadded:: 2.2
213
214
215.. function:: relpath(path[, start])
216
217 Return a relative filepath to *path* either from the current directory or from
218 an optional *start* point.
219
220 *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix.
221
222 .. versionadded:: 2.6
223
224
225.. function:: samefile(path1, path2)
226
227 Return ``True`` if both pathname arguments refer to the same file or directory
228 (as indicated by device number and i-node number). Raise an exception if a
229 :func:`os.stat` call on either pathname fails. Availability: Macintosh, Unix.
230
231
232.. function:: sameopenfile(fp1, fp2)
233
234 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
235 Availability: Macintosh, Unix.
236
237
238.. function:: samestat(stat1, stat2)
239
240 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
241 These structures may have been returned by :func:`fstat`, :func:`lstat`, or
242 :func:`stat`. This function implements the underlying comparison used by
243 :func:`samefile` and :func:`sameopenfile`. Availability: Macintosh, Unix.
244
245
246.. function:: split(path)
247
248 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the last
249 pathname component and *head* is everything leading up to that. The *tail* part
250 will never contain a slash; if *path* ends in a slash, *tail* will be empty. If
251 there is no slash in *path*, *head* will be empty. If *path* is empty, both
252 *head* and *tail* are empty. Trailing slashes are stripped from *head* unless
253 it is the root (one or more slashes only). In nearly all cases, ``join(head,
254 tail)`` equals *path* (the only exception being when there were multiple slashes
255 separating *head* from *tail*).
256
257
258.. function:: splitdrive(path)
259
260 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
261 a drive specification or the empty string. On systems which do not use drive
262 specifications, *drive* will always be the empty string. In all cases, ``drive
263 + tail`` will be the same as *path*.
264
265 .. versionadded:: 1.3
266
267
268.. function:: splitext(path)
269
270 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
271 path``, and *ext* is empty or begins with a period and contains at most one
272 period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
273 returns ``('.cshrc', '')``.
274
275 .. versionchanged:: 2.6
276 Earlier versions could produce an empty root when the only period was the
277 first character.
278
279
280.. function:: splitunc(path)
281
282 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
283 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
284 the path (such as ``r'\path\file.ext'``). For paths containing drive letters,
285 *unc* will always be the empty string. Availability: Windows.
286
287
288.. function:: walk(path, visit, arg)
289
290 Calls the function *visit* with arguments ``(arg, dirname, names)`` for each
291 directory in the directory tree rooted at *path* (including *path* itself, if it
292 is a directory). The argument *dirname* specifies the visited directory, the
293 argument *names* lists the files in the directory (gotten from
294 ``os.listdir(dirname)``). The *visit* function may modify *names* to influence
295 the set of directories visited below *dirname*, e.g. to avoid visiting certain
296 parts of the tree. (The object referred to by *names* must be modified in
297 place, using :keyword:`del` or slice assignment.)
298
299 .. note::
300
301 Symbolic links to directories are not treated as subdirectories, and that
302 :func:`walk` therefore will not visit them. To visit linked directories you must
303 identify them with ``os.path.islink(file)`` and ``os.path.isdir(file)``, and
304 invoke :func:`walk` as necessary.
305
306 .. note::
307
Georg Brandlcf3fb252007-10-21 10:52:38 +0000308 The newer :func:`os.walk` :term:`generator` supplies similar functionality
309 and can be easier to use.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311
312.. data:: supports_unicode_filenames
313
314 True if arbitrary Unicode strings can be used as file names (within limitations
315 imposed by the file system), and if :func:`os.listdir` returns Unicode strings
316 for a Unicode argument.
317
318 .. versionadded:: 2.3
319