blob: bf0dface7e9fd202b491ef049c9248e65de14631 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`os.path` --- Common pathname manipulations
2================================================
3
4.. module:: os.path
5 :synopsis: Operations on pathnames.
6
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007**Source code:** :source:`Lib/posixpath.py` (for POSIX),
8:source:`Lib/ntpath.py` (for Windows NT),
9and :source:`Lib/macpath.py` (for Macintosh)
10
Georg Brandl116aa622007-08-15 14:28:22 +000011.. index:: single: path; operations
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013--------------
14
Georg Brandl116aa622007-08-15 14:28:22 +000015This module implements some useful functions on pathnames. To read or
16write files see :func:`open`, and for accessing the filesystem see the
Martin v. Löwis651423c2008-10-07 07:03:04 +000017:mod:`os` module. The path parameters can be passed as either strings,
18or bytes. Applications are encouraged to represent file names as
19(Unicode) character strings. Unfortunately, some file names may not be
20representable as strings on Unix, so applications that need to support
21arbitrary file names on Unix should use bytes objects to represent
22path names. Vice versa, using bytes objects cannot represent all file
23names on Windows (in the standard ``mbcs`` encoding), hence Windows
24applications should use string objects to access all files.
Georg Brandl116aa622007-08-15 14:28:22 +000025
R David Murraya4e700c2013-01-06 16:13:10 -050026Unlike a unix shell, Python does not do any *automatic* path expansions.
27Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
28explicitly when an application desires shell-like path expansion. (See also
29the :mod:`glob` module.)
30
Antoine Pitrou31119e42013-11-22 17:38:12 +010031
32.. seealso::
33 The :mod:`pathlib` module offers high-level path objects.
34
35
Georg Brandl76e55382008-10-08 16:34:57 +000036.. note::
37
38 All of these functions accept either only bytes or only string objects as
39 their parameters. The result is an object of the same type, if a path or
40 file name is returned.
41
Georg Brandl116aa622007-08-15 14:28:22 +000042
Benjamin Petersond23f8222009-04-05 19:13:16 +000043.. note::
44
45 Since different operating systems have different path name conventions, there
46 are several versions of this module in the standard library. The
47 :mod:`os.path` module is always the path module suitable for the operating
48 system Python is running on, and therefore usable for local paths. However,
49 you can also import and use the individual modules if you want to manipulate
50 a path that is *always* in one of the different formats. They all have the
51 same interface:
52
53 * :mod:`posixpath` for UNIX-style paths
54 * :mod:`ntpath` for Windows paths
55 * :mod:`macpath` for old-style MacOS paths
Benjamin Petersond23f8222009-04-05 19:13:16 +000056
57
Georg Brandl116aa622007-08-15 14:28:22 +000058.. function:: abspath(path)
59
60 Return a normalized absolutized version of the pathname *path*. On most
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080061 platforms, this is equivalent to calling the function :func:`normpath` as
62 follows: ``normpath(join(os.getcwd(), path))``.
Georg Brandl116aa622007-08-15 14:28:22 +000063
Georg Brandl116aa622007-08-15 14:28:22 +000064
65.. function:: basename(path)
66
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080067 Return the base name of pathname *path*. This is the second element of the
68 pair returned by passing *path* to the function :func:`split`. Note that
69 the result of this function is different
Georg Brandl116aa622007-08-15 14:28:22 +000070 from the Unix :program:`basename` program; where :program:`basename` for
71 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
72 empty string (``''``).
73
74
Serhiy Storchaka38220932015-03-31 15:31:53 +030075.. function:: commonpath(paths)
76
77 Return the longest common sub-path of each pathname in the sequence
78 *paths*. Raise ValueError if *paths* contains both absolute and relative
79 pathnames, or if *paths* is empty. Unlike :func:`commonprefix`, this
80 returns a valid path.
81
82 Availability: Unix, Windows
83
84 .. versionadded:: 3.5
85
86
Georg Brandl116aa622007-08-15 14:28:22 +000087.. function:: commonprefix(list)
88
Serhiy Storchaka38220932015-03-31 15:31:53 +030089 Return the longest path prefix (taken character-by-character) that is a
90 prefix of all paths in *list*. If *list* is empty, return the empty string
Yury Selivanov80ac11f2015-08-17 23:43:43 -040091 (``''``).
92
93 .. note::
94
95 This function may return invalid paths because it works a
96 character at a time. To obtain a valid path, see
97 :func:`commonpath`.
98
99 ::
100
Yury Selivanovde115612015-08-19 09:53:28 -0400101 >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
102 '/usr/l'
Yury Selivanov80ac11f2015-08-17 23:43:43 -0400103
Yury Selivanovde115612015-08-19 09:53:28 -0400104 >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
105 '/usr'
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107
108.. function:: dirname(path)
109
Chris Jerdonek0b502ff2012-11-25 20:38:01 -0800110 Return the directory name of pathname *path*. This is the first element of
111 the pair returned by passing *path* to the function :func:`split`.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. function:: exists(path)
115
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100116 Return ``True`` if *path* refers to an existing path or an open
117 file descriptor. Returns ``False`` for broken symbolic links. On
118 some platforms, this function may return ``False`` if permission is
119 not granted to execute :func:`os.stat` on the requested file, even
Georg Brandl116aa622007-08-15 14:28:22 +0000120 if the *path* physically exists.
121
Richard Oudkerk2240ac12012-07-06 12:05:32 +0100122 .. versionchanged:: 3.3
123 *path* can now be an integer: ``True`` is returned if it is an
124 open file descriptor, ``False`` otherwise.
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127.. function:: lexists(path)
128
129 Return ``True`` if *path* refers to an existing path. Returns ``True`` for
130 broken symbolic links. Equivalent to :func:`exists` on platforms lacking
131 :func:`os.lstat`.
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134.. function:: expanduser(path)
135
136 On Unix and Windows, return the argument with an initial component of ``~`` or
137 ``~user`` replaced by that *user*'s home directory.
138
139 .. index:: module: pwd
140
141 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
142 if it is set; otherwise the current user's home directory is looked up in the
143 password directory through the built-in module :mod:`pwd`. An initial ``~user``
144 is looked up directly in the password directory.
145
146 On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
147 otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
148 used. An initial ``~user`` is handled by stripping the last directory component
149 from the created user path derived above.
150
151 If the expansion fails or if the path does not begin with a tilde, the path is
152 returned unchanged.
153
154
155.. function:: expandvars(path)
156
157 Return the argument with environment variables expanded. Substrings of the form
158 ``$name`` or ``${name}`` are replaced by the value of environment variable
159 *name*. Malformed variable names and references to non-existing variables are
160 left unchanged.
161
162 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
163 ``${name}``.
164
165
166.. function:: getatime(path)
167
168 Return the time of last access of *path*. The return value is a number giving
169 the number of seconds since the epoch (see the :mod:`time` module). Raise
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200170 :exc:`OSError` if the file does not exist or is inaccessible.
Georg Brandl116aa622007-08-15 14:28:22 +0000171
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200172 If :func:`os.stat_float_times` returns ``True``, the result is a floating point
Georg Brandl55ac8f02007-09-01 13:51:09 +0000173 number.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175
176.. function:: getmtime(path)
177
178 Return the time of last modification of *path*. The return value is a number
179 giving the number of seconds since the epoch (see the :mod:`time` module).
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200180 Raise :exc:`OSError` if the file does not exist or is inaccessible.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200182 If :func:`os.stat_float_times` returns ``True``, the result is a floating point
Georg Brandl55ac8f02007-09-01 13:51:09 +0000183 number.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185
186.. function:: getctime(path)
187
188 Return the system's ctime which, on some systems (like Unix) is the time of the
Georg Brandlf6324942013-10-06 09:52:55 +0200189 last metadata change, and, on others (like Windows), is the creation time for *path*.
Georg Brandl116aa622007-08-15 14:28:22 +0000190 The return value is a number giving the number of seconds since the epoch (see
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200191 the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or
Georg Brandl116aa622007-08-15 14:28:22 +0000192 is inaccessible.
193
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195.. function:: getsize(path)
196
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200197 Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does
Georg Brandl116aa622007-08-15 14:28:22 +0000198 not exist or is inaccessible.
199
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201.. function:: isabs(path)
202
Christian Heimesaf98da12008-01-27 15:18:18 +0000203 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
204 begins with a slash, on Windows that it begins with a (back)slash after chopping
205 off a potential drive letter.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207
208.. function:: isfile(path)
209
210 Return ``True`` if *path* is an existing regular file. This follows symbolic
211 links, so both :func:`islink` and :func:`isfile` can be true for the same path.
212
213
214.. function:: isdir(path)
215
216 Return ``True`` if *path* is an existing directory. This follows symbolic
217 links, so both :func:`islink` and :func:`isdir` can be true for the same path.
218
219
220.. function:: islink(path)
221
222 Return ``True`` if *path* refers to a directory entry that is a symbolic link.
Ned Deily32db4382016-06-04 09:40:40 -0700223 Always ``False`` if symbolic links are not supported by the Python runtime.
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225
226.. function:: ismount(path)
227
Larry Hastings3732ed22014-03-15 21:13:56 -0700228 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a
229 file system where a different file system has been mounted. On POSIX, the
230 function checks whether *path*'s parent, :file:`path/..`, is on a different
231 device than *path*, or whether :file:`path/..` and *path* point to the same
232 i-node on the same device --- this should detect mount points for all Unix
233 and POSIX variants. On Windows, a drive letter root and a share UNC are
234 always mount points, and for any other path ``GetVolumePathName`` is called
235 to see if it is different from the input path.
236
237 .. versionadded:: 3.4
238 Support for detecting non-root mount points on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240
Zachary Warea13dab42014-10-10 16:03:14 -0500241.. function:: join(path, *paths)
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Zachary Warea13dab42014-10-10 16:03:14 -0500243 Join one or more path components intelligently. The return value is the
244 concatenation of *path* and any members of *\*paths* with exactly one
245 directory separator (``os.sep``) following each non-empty part except the
246 last, meaning that the result will only end in a separator if the last
247 part is empty. If a component is an absolute path, all previous
248 components are thrown away and joining continues from the absolute path
249 component.
250
251 On Windows, the drive letter is not reset when an absolute path component
252 (e.g., ``r'\foo'``) is encountered. If a component contains a drive
253 letter, all previous components are thrown away and the drive letter is
254 reset. Note that since there is a current directory for each drive,
255 ``os.path.join("c:", "foo")`` represents a path relative to the current
256 directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258
259.. function:: normcase(path)
260
Benjamin Petersond23f8222009-04-05 19:13:16 +0000261 Normalize the case of a pathname. On Unix and Mac OS X, this returns the
262 path unchanged; on case-insensitive filesystems, it converts the path to
263 lowercase. On Windows, it also converts forward slashes to backward slashes.
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +0000264 Raise a TypeError if the type of *path* is not ``str`` or ``bytes``.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
267.. function:: normpath(path)
268
Terry Jan Reedyec6e1322013-03-17 15:21:26 -0400269 Normalize a pathname by collapsing redundant separators and up-level
270 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
271 become ``A/B``. This string manipulation may change the meaning of a path
272 that contains symbolic links. On Windows, it converts forward slashes to
Terry Jan Reedyf3460412013-03-17 15:28:10 -0400273 backward slashes. To normalize case, use :func:`normcase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275
276.. function:: realpath(path)
277
278 Return the canonical path of the specified filename, eliminating any symbolic
279 links encountered in the path (if they are supported by the operating system).
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Benjamin Peterson409a1be2014-03-20 12:39:53 -0500282.. function:: relpath(path, start=os.curdir)
Georg Brandl116aa622007-08-15 14:28:22 +0000283
R David Murrayce10fab2013-07-12 17:43:11 -0400284 Return a relative filepath to *path* either from the current directory or
285 from an optional *start* directory. This is a path computation: the
286 filesystem is not accessed to confirm the existence or nature of *path* or
287 *start*.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Benjamin Petersonf650e462010-05-06 23:03:05 +0000289 *start* defaults to :attr:`os.curdir`.
290
Antoine Pitrouf10f1622010-12-12 20:17:29 +0000291 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294.. function:: samefile(path1, path2)
295
Brian Curtind40e6f72010-07-08 21:39:08 +0000296 Return ``True`` if both pathname arguments refer to the same file or directory.
Larry Hastings3732ed22014-03-15 21:13:56 -0700297 This is determined by the device number and i-node number and raises an
Martin Panter7462b6492015-11-02 03:37:02 +0000298 exception if an :func:`os.stat` call on either pathname fails.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000299
Antoine Pitrouf10f1622010-12-12 20:17:29 +0000300 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Georg Brandlb3823372010-07-10 08:58:37 +0000302 .. versionchanged:: 3.2
303 Added Windows support.
Brian Curtinc7395692010-07-09 15:15:09 +0000304
Brian Curtin490b32a2012-12-26 07:03:03 -0600305 .. versionchanged:: 3.4
306 Windows now uses the same implementation as all other platforms.
307
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309.. function:: sameopenfile(fp1, fp2)
310
311 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000312
Brian Curtin62857742010-09-06 17:07:27 +0000313 Availability: Unix, Windows.
314
Georg Brandl61063cc2012-06-24 22:48:30 +0200315 .. versionchanged:: 3.2
316 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318
319.. function:: samestat(stat1, stat2)
320
321 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
Serhiy Storchakadab83542013-10-13 20:12:43 +0300322 These structures may have been returned by :func:`os.fstat`,
323 :func:`os.lstat`, or :func:`os.stat`. This function implements the
324 underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000325
Brian Curtin490b32a2012-12-26 07:03:03 -0600326 Availability: Unix, Windows.
327
328 .. versionchanged:: 3.4
329 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331
332.. function:: split(path)
333
Georg Brandl539c1652010-10-14 06:46:08 +0000334 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
335 last pathname component and *head* is everything leading up to that. The
336 *tail* part will never contain a slash; if *path* ends in a slash, *tail*
337 will be empty. If there is no slash in *path*, *head* will be empty. If
338 *path* is empty, both *head* and *tail* are empty. Trailing slashes are
339 stripped from *head* unless it is the root (one or more slashes only). In
340 all cases, ``join(head, tail)`` returns a path to the same location as *path*
Chris Jerdonek0b502ff2012-11-25 20:38:01 -0800341 (but the strings may differ). Also see the functions :func:`dirname` and
342 :func:`basename`.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344
345.. function:: splitdrive(path)
346
347 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
Mark Hammond5a607a32009-05-06 08:04:54 +0000348 a mount point or the empty string. On systems which do not use drive
Georg Brandl116aa622007-08-15 14:28:22 +0000349 specifications, *drive* will always be the empty string. In all cases, ``drive
350 + tail`` will be the same as *path*.
351
Mark Hammond5a607a32009-05-06 08:04:54 +0000352 On Windows, splits a pathname into drive/UNC sharepoint and relative path.
353
354 If the path contains a drive letter, drive will contain everything
355 up to and including the colon.
356 e.g. ``splitdrive("c:/dir")`` returns ``("c:", "/dir")``
357
358 If the path contains a UNC path, drive will contain the host name
359 and share, up to but not including the fourth separator.
360 e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")``
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363.. function:: splitext(path)
364
365 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
366 path``, and *ext* is empty or begins with a period and contains at most one
367 period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
368 returns ``('.cshrc', '')``.
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371.. function:: splitunc(path)
372
Mark Hammond5a607a32009-05-06 08:04:54 +0000373 .. deprecated:: 3.1
374 Use *splitdrive* instead.
375
Georg Brandl116aa622007-08-15 14:28:22 +0000376 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
377 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
378 the path (such as ``r'\path\file.ext'``). For paths containing drive letters,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000379 *unc* will always be the empty string.
380
381 Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
Georg Brandl116aa622007-08-15 14:28:22 +0000384.. data:: supports_unicode_filenames
385
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200386 ``True`` if arbitrary Unicode strings can be used as file names (within limitations
Victor Stinnerb55e4982010-09-11 00:22:12 +0000387 imposed by the file system).