blob: dac479a0b720da7466b86f3842a2161f9cc7fe7e [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`os.path` --- Common pathname manipulations
2================================================
3
4.. module:: os.path
5 :synopsis: Operations on pathnames.
6
Georg Brandl8ec7f652007-08-15 14:28:01 +00007.. index:: single: path; operations
8
9This module implements some useful functions on pathnames. To read or
10write files see :func:`open`, and for accessing the filesystem see the
11:mod:`os` module.
12
Georg Brandl16a57f62009-04-27 15:29:09 +000013.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
15 On Windows, many of these functions do not properly support UNC pathnames.
16 :func:`splitunc` and :func:`ismount` do handle them correctly.
17
18
R David Murrayb847c7f2013-01-06 16:14:57 -050019Unlike a unix shell, Python does not do any *automatic* path expansions.
20Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
21explicitly when an application desires shell-like path expansion. (See also
22the :mod:`glob` module.)
23
Georg Brandl5d196102009-04-05 10:41:02 +000024.. note::
25
26 Since different operating systems have different path name conventions, there
27 are several versions of this module in the standard library. The
28 :mod:`os.path` module is always the path module suitable for the operating
29 system Python is running on, and therefore usable for local paths. However,
30 you can also import and use the individual modules if you want to manipulate
31 a path that is *always* in one of the different formats. They all have the
32 same interface:
33
34 * :mod:`posixpath` for UNIX-style paths
35 * :mod:`ntpath` for Windows paths
36 * :mod:`macpath` for old-style MacOS paths
37 * :mod:`os2emxpath` for OS/2 EMX paths
38
39
Georg Brandl8ec7f652007-08-15 14:28:01 +000040.. function:: abspath(path)
41
42 Return a normalized absolutized version of the pathname *path*. On most
Chris Jerdonek55b4cfb2012-11-25 20:35:23 -080043 platforms, this is equivalent to calling the function :func:`normpath` as
44 follows: ``normpath(join(os.getcwd(), path))``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46 .. versionadded:: 1.5.2
47
48
49.. function:: basename(path)
50
Chris Jerdonek55b4cfb2012-11-25 20:35:23 -080051 Return the base name of pathname *path*. This is the second element of the
52 pair returned by passing *path* to the function :func:`split`. Note that
53 the result of this function is different
Georg Brandl8ec7f652007-08-15 14:28:01 +000054 from the Unix :program:`basename` program; where :program:`basename` for
55 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
56 empty string (``''``).
57
58
59.. function:: commonprefix(list)
60
61 Return the longest path prefix (taken character-by-character) that is a prefix
62 of all paths in *list*. If *list* is empty, return the empty string (``''``).
63 Note that this may return invalid paths because it works a character at a time.
64
65
66.. function:: dirname(path)
67
Chris Jerdonek55b4cfb2012-11-25 20:35:23 -080068 Return the directory name of pathname *path*. This is the first element of
69 the pair returned by passing *path* to the function :func:`split`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000070
71
72.. function:: exists(path)
73
74 Return ``True`` if *path* refers to an existing path. Returns ``False`` for
75 broken symbolic links. On some platforms, this function may return ``False`` if
76 permission is not granted to execute :func:`os.stat` on the requested file, even
77 if the *path* physically exists.
78
79
80.. function:: lexists(path)
81
82 Return ``True`` if *path* refers to an existing path. Returns ``True`` for
83 broken symbolic links. Equivalent to :func:`exists` on platforms lacking
84 :func:`os.lstat`.
85
86 .. versionadded:: 2.4
87
88
89.. function:: expanduser(path)
90
91 On Unix and Windows, return the argument with an initial component of ``~`` or
92 ``~user`` replaced by that *user*'s home directory.
93
94 .. index:: module: pwd
95
96 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
97 if it is set; otherwise the current user's home directory is looked up in the
98 password directory through the built-in module :mod:`pwd`. An initial ``~user``
99 is looked up directly in the password directory.
100
101 On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
102 otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
103 used. An initial ``~user`` is handled by stripping the last directory component
104 from the created user path derived above.
105
106 If the expansion fails or if the path does not begin with a tilde, the path is
107 returned unchanged.
108
109
110.. function:: expandvars(path)
111
112 Return the argument with environment variables expanded. Substrings of the form
113 ``$name`` or ``${name}`` are replaced by the value of environment variable
114 *name*. Malformed variable names and references to non-existing variables are
115 left unchanged.
116
117 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
118 ``${name}``.
119
120
121.. function:: getatime(path)
122
123 Return the time of last access of *path*. The return value is a number giving
124 the number of seconds since the epoch (see the :mod:`time` module). Raise
125 :exc:`os.error` if the file does not exist or is inaccessible.
126
127 .. versionadded:: 1.5.2
128
129 .. versionchanged:: 2.3
130 If :func:`os.stat_float_times` returns True, the result is a floating point
131 number.
132
133
134.. function:: getmtime(path)
135
136 Return the time of last modification of *path*. The return value is a number
137 giving the number of seconds since the epoch (see the :mod:`time` module).
138 Raise :exc:`os.error` if the file does not exist or is inaccessible.
139
140 .. versionadded:: 1.5.2
141
142 .. versionchanged:: 2.3
143 If :func:`os.stat_float_times` returns True, the result is a floating point
144 number.
145
146
147.. function:: getctime(path)
148
149 Return the system's ctime which, on some systems (like Unix) is the time of the
150 last change, and, on others (like Windows), is the creation time for *path*.
151 The return value is a number giving the number of seconds since the epoch (see
152 the :mod:`time` module). Raise :exc:`os.error` if the file does not exist or
153 is inaccessible.
154
155 .. versionadded:: 2.3
156
157
158.. function:: getsize(path)
159
160 Return the size, in bytes, of *path*. Raise :exc:`os.error` if the file does
161 not exist or is inaccessible.
162
163 .. versionadded:: 1.5.2
164
165
166.. function:: isabs(path)
167
Georg Brandlfe7dd502008-01-26 09:43:35 +0000168 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
Georg Brandl05225482008-01-26 11:02:22 +0000169 begins with a slash, on Windows that it begins with a (back)slash after chopping
Georg Brandlfe7dd502008-01-26 09:43:35 +0000170 off a potential drive letter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
172
173.. function:: isfile(path)
174
175 Return ``True`` if *path* is an existing regular file. This follows symbolic
176 links, so both :func:`islink` and :func:`isfile` can be true for the same path.
177
178
179.. function:: isdir(path)
180
181 Return ``True`` if *path* is an existing directory. This follows symbolic
182 links, so both :func:`islink` and :func:`isdir` can be true for the same path.
183
184
185.. function:: islink(path)
186
187 Return ``True`` if *path* refers to a directory entry that is a symbolic link.
188 Always ``False`` if symbolic links are not supported.
189
190
191.. function:: ismount(path)
192
193 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file
194 system where a different file system has been mounted. The function checks
195 whether *path*'s parent, :file:`path/..`, is on a different device than *path*,
196 or whether :file:`path/..` and *path* point to the same i-node on the same
197 device --- this should detect mount points for all Unix and POSIX variants.
198
199
200.. function:: join(path1[, path2[, ...]])
201
202 Join one or more path components intelligently. If any component is an absolute
203 path, all previous components (on Windows, including the previous drive letter,
204 if there was one) are thrown away, and joining continues. The return value is
205 the concatenation of *path1*, and optionally *path2*, etc., with exactly one
R David Murray17e2b402011-06-23 21:19:25 -0400206 directory separator (``os.sep``) following each non-empty part except the last.
207 (This means that an empty last part will result in a path that ends with a
208 separator.) Note that on Windows, since there is a current directory for
209 each drive, ``os.path.join("c:", "foo")`` represents a path relative to the
210 current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
212
213.. function:: normcase(path)
214
Georg Brandl89b12962009-04-05 10:29:57 +0000215 Normalize the case of a pathname. On Unix and Mac OS X, this returns the
216 path unchanged; on case-insensitive filesystems, it converts the path to
217 lowercase. On Windows, it also converts forward slashes to backward slashes.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218
219
220.. function:: normpath(path)
221
Terry Jan Reedy3e50fb32013-03-17 15:21:26 -0400222 Normalize a pathname by collapsing redundant separators and up-level
223 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
224 become ``A/B``. This string manipulation may change the meaning of a path
225 that contains symbolic links. On Windows, it converts forward slashes to
226 backward slashes. To normalize case, use :func:`normcase`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227
228
229.. function:: realpath(path)
230
231 Return the canonical path of the specified filename, eliminating any symbolic
232 links encountered in the path (if they are supported by the operating system).
233
234 .. versionadded:: 2.2
235
236
237.. function:: relpath(path[, start])
238
239 Return a relative filepath to *path* either from the current directory or from
240 an optional *start* point.
241
Benjamin Peterson7aaef842010-05-06 22:33:46 +0000242 *start* defaults to :attr:`os.curdir`.
243
244 Availability: Windows, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
246 .. versionadded:: 2.6
247
248
249.. function:: samefile(path1, path2)
250
251 Return ``True`` if both pathname arguments refer to the same file or directory
252 (as indicated by device number and i-node number). Raise an exception if a
Benjamin Peterson7aaef842010-05-06 22:33:46 +0000253 :func:`os.stat` call on either pathname fails.
254
255 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
257
258.. function:: sameopenfile(fp1, fp2)
259
260 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
Benjamin Peterson7aaef842010-05-06 22:33:46 +0000261
Georg Brandl9af94982008-09-13 17:41:16 +0000262 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000263
264
265.. function:: samestat(stat1, stat2)
266
267 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
268 These structures may have been returned by :func:`fstat`, :func:`lstat`, or
269 :func:`stat`. This function implements the underlying comparison used by
Benjamin Peterson7aaef842010-05-06 22:33:46 +0000270 :func:`samefile` and :func:`sameopenfile`.
271
272 Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273
274
275.. function:: split(path)
276
Georg Brandl420cca92010-11-26 07:21:01 +0000277 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
278 last pathname component and *head* is everything leading up to that. The
279 *tail* part will never contain a slash; if *path* ends in a slash, *tail*
280 will be empty. If there is no slash in *path*, *head* will be empty. If
281 *path* is empty, both *head* and *tail* are empty. Trailing slashes are
282 stripped from *head* unless it is the root (one or more slashes only). In
283 all cases, ``join(head, tail)`` returns a path to the same location as *path*
Chris Jerdonek55b4cfb2012-11-25 20:35:23 -0800284 (but the strings may differ). Also see the functions :func:`dirname` and
285 :func:`basename`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
287
288.. function:: splitdrive(path)
289
290 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
291 a drive specification or the empty string. On systems which do not use drive
292 specifications, *drive* will always be the empty string. In all cases, ``drive
293 + tail`` will be the same as *path*.
294
295 .. versionadded:: 1.3
296
297
298.. function:: splitext(path)
299
300 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
301 path``, and *ext* is empty or begins with a period and contains at most one
302 period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
303 returns ``('.cshrc', '')``.
304
305 .. versionchanged:: 2.6
306 Earlier versions could produce an empty root when the only period was the
307 first character.
308
309
310.. function:: splitunc(path)
311
312 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
313 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
314 the path (such as ``r'\path\file.ext'``). For paths containing drive letters,
Benjamin Peterson7aaef842010-05-06 22:33:46 +0000315 *unc* will always be the empty string.
316
317 Availability: Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318
319
320.. function:: walk(path, visit, arg)
321
322 Calls the function *visit* with arguments ``(arg, dirname, names)`` for each
323 directory in the directory tree rooted at *path* (including *path* itself, if it
324 is a directory). The argument *dirname* specifies the visited directory, the
325 argument *names* lists the files in the directory (gotten from
326 ``os.listdir(dirname)``). The *visit* function may modify *names* to influence
327 the set of directories visited below *dirname*, e.g. to avoid visiting certain
328 parts of the tree. (The object referred to by *names* must be modified in
329 place, using :keyword:`del` or slice assignment.)
330
331 .. note::
332
333 Symbolic links to directories are not treated as subdirectories, and that
334 :func:`walk` therefore will not visit them. To visit linked directories you must
335 identify them with ``os.path.islink(file)`` and ``os.path.isdir(file)``, and
336 invoke :func:`walk` as necessary.
337
Georg Brandl16a57f62009-04-27 15:29:09 +0000338 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339
Ezio Melotti510ff542012-05-03 19:21:40 +0300340 This function is deprecated and has been removed in Python 3 in favor of
Benjamin Peterson0893a0a2008-05-09 00:27:01 +0000341 :func:`os.walk`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342
343
344.. data:: supports_unicode_filenames
345
346 True if arbitrary Unicode strings can be used as file names (within limitations
Victor Stinner46287f52010-09-13 20:31:34 +0000347 imposed by the file system).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
349 .. versionadded:: 2.3
350