blob: 0d2ad0441796f492ff3945b48527ba077e45eafc [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
Georg Brandl116aa622007-08-15 14:28:22 +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
Martin v. Löwis651423c2008-10-07 07:03:04 +000011:mod:`os` module. The path parameters can be passed as either strings,
12or bytes. Applications are encouraged to represent file names as
13(Unicode) character strings. Unfortunately, some file names may not be
14representable as strings on Unix, so applications that need to support
15arbitrary file names on Unix should use bytes objects to represent
16path names. Vice versa, using bytes objects cannot represent all file
17names on Windows (in the standard ``mbcs`` encoding), hence Windows
18applications should use string objects to access all files.
Georg Brandl116aa622007-08-15 14:28:22 +000019
R David Murraya4e700c2013-01-06 16:13:10 -050020Unlike a unix shell, Python does not do any *automatic* path expansions.
21Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
22explicitly when an application desires shell-like path expansion. (See also
23the :mod:`glob` module.)
24
Georg Brandl76e55382008-10-08 16:34:57 +000025.. note::
26
27 All of these functions accept either only bytes or only string objects as
28 their parameters. The result is an object of the same type, if a path or
29 file name is returned.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031
Benjamin Petersond23f8222009-04-05 19:13:16 +000032.. note::
33
34 Since different operating systems have different path name conventions, there
35 are several versions of this module in the standard library. The
36 :mod:`os.path` module is always the path module suitable for the operating
37 system Python is running on, and therefore usable for local paths. However,
38 you can also import and use the individual modules if you want to manipulate
39 a path that is *always* in one of the different formats. They all have the
40 same interface:
41
42 * :mod:`posixpath` for UNIX-style paths
43 * :mod:`ntpath` for Windows paths
44 * :mod:`macpath` for old-style MacOS paths
Benjamin Petersond23f8222009-04-05 19:13:16 +000045
46
Georg Brandl116aa622007-08-15 14:28:22 +000047.. function:: abspath(path)
48
49 Return a normalized absolutized version of the pathname *path*. On most
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080050 platforms, this is equivalent to calling the function :func:`normpath` as
51 follows: ``normpath(join(os.getcwd(), path))``.
Georg Brandl116aa622007-08-15 14:28:22 +000052
Georg Brandl116aa622007-08-15 14:28:22 +000053
54.. function:: basename(path)
55
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080056 Return the base name of pathname *path*. This is the second element of the
57 pair returned by passing *path* to the function :func:`split`. Note that
58 the result of this function is different
Georg Brandl116aa622007-08-15 14:28:22 +000059 from the Unix :program:`basename` program; where :program:`basename` for
60 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
61 empty string (``''``).
62
63
64.. function:: commonprefix(list)
65
66 Return the longest path prefix (taken character-by-character) that is a prefix
67 of all paths in *list*. If *list* is empty, return the empty string (``''``).
68 Note that this may return invalid paths because it works a character at a time.
69
70
71.. function:: dirname(path)
72
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080073 Return the directory name of pathname *path*. This is the first element of
74 the pair returned by passing *path* to the function :func:`split`.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76
77.. function:: exists(path)
78
Richard Oudkerk2240ac12012-07-06 12:05:32 +010079 Return ``True`` if *path* refers to an existing path or an open
80 file descriptor. Returns ``False`` for broken symbolic links. On
81 some platforms, this function may return ``False`` if permission is
82 not granted to execute :func:`os.stat` on the requested file, even
Georg Brandl116aa622007-08-15 14:28:22 +000083 if the *path* physically exists.
84
Richard Oudkerk2240ac12012-07-06 12:05:32 +010085 .. versionchanged:: 3.3
86 *path* can now be an integer: ``True`` is returned if it is an
87 open file descriptor, ``False`` otherwise.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089
90.. function:: lexists(path)
91
92 Return ``True`` if *path* refers to an existing path. Returns ``True`` for
93 broken symbolic links. Equivalent to :func:`exists` on platforms lacking
94 :func:`os.lstat`.
95
Georg Brandl116aa622007-08-15 14:28:22 +000096
97.. function:: expanduser(path)
98
99 On Unix and Windows, return the argument with an initial component of ``~`` or
100 ``~user`` replaced by that *user*'s home directory.
101
102 .. index:: module: pwd
103
104 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
105 if it is set; otherwise the current user's home directory is looked up in the
106 password directory through the built-in module :mod:`pwd`. An initial ``~user``
107 is looked up directly in the password directory.
108
109 On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
110 otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
111 used. An initial ``~user`` is handled by stripping the last directory component
112 from the created user path derived above.
113
114 If the expansion fails or if the path does not begin with a tilde, the path is
115 returned unchanged.
116
117
118.. function:: expandvars(path)
119
120 Return the argument with environment variables expanded. Substrings of the form
121 ``$name`` or ``${name}`` are replaced by the value of environment variable
122 *name*. Malformed variable names and references to non-existing variables are
123 left unchanged.
124
125 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
126 ``${name}``.
127
128
129.. function:: getatime(path)
130
131 Return the time of last access of *path*. The return value is a number giving
132 the number of seconds since the epoch (see the :mod:`time` module). Raise
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200133 :exc:`OSError` if the file does not exist or is inaccessible.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
Georg Brandl55ac8f02007-09-01 13:51:09 +0000135 If :func:`os.stat_float_times` returns True, the result is a floating point
136 number.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138
139.. function:: getmtime(path)
140
141 Return the time of last modification of *path*. The return value is a number
142 giving the number of seconds since the epoch (see the :mod:`time` module).
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200143 Raise :exc:`OSError` if the file does not exist or is inaccessible.
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Georg Brandl55ac8f02007-09-01 13:51:09 +0000145 If :func:`os.stat_float_times` returns True, the result is a floating point
146 number.
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148
149.. function:: getctime(path)
150
151 Return the system's ctime which, on some systems (like Unix) is the time of the
152 last change, and, on others (like Windows), is the creation time for *path*.
153 The return value is a number giving the number of seconds since the epoch (see
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200154 the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or
Georg Brandl116aa622007-08-15 14:28:22 +0000155 is inaccessible.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. function:: getsize(path)
159
Andrew Svetlov618c2e12012-12-15 22:59:24 +0200160 Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does
Georg Brandl116aa622007-08-15 14:28:22 +0000161 not exist or is inaccessible.
162
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164.. function:: isabs(path)
165
Christian Heimesaf98da12008-01-27 15:18:18 +0000166 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
167 begins with a slash, on Windows that it begins with a (back)slash after chopping
168 off a potential drive letter.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170
171.. function:: isfile(path)
172
173 Return ``True`` if *path* is an existing regular file. This follows symbolic
174 links, so both :func:`islink` and :func:`isfile` can be true for the same path.
175
176
177.. function:: isdir(path)
178
179 Return ``True`` if *path* is an existing directory. This follows symbolic
180 links, so both :func:`islink` and :func:`isdir` can be true for the same path.
181
182
183.. function:: islink(path)
184
185 Return ``True`` if *path* refers to a directory entry that is a symbolic link.
186 Always ``False`` if symbolic links are not supported.
187
188
189.. function:: ismount(path)
190
191 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file
192 system where a different file system has been mounted. The function checks
193 whether *path*'s parent, :file:`path/..`, is on a different device than *path*,
194 or whether :file:`path/..` and *path* point to the same i-node on the same
195 device --- this should detect mount points for all Unix and POSIX variants.
196
197
198.. function:: join(path1[, path2[, ...]])
199
200 Join one or more path components intelligently. If any component is an absolute
201 path, all previous components (on Windows, including the previous drive letter,
202 if there was one) are thrown away, and joining continues. The return value is
203 the concatenation of *path1*, and optionally *path2*, etc., with exactly one
R David Murray24eb4bc2011-06-23 21:26:13 -0400204 directory separator (``os.sep``) following each non-empty part except the last.
205 (This means that an empty last part will result in a path that ends with a
206 separator.) Note that on Windows, since there is a current directory for
207 each drive, ``os.path.join("c:", "foo")`` represents a path relative to the
208 current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210
211.. function:: normcase(path)
212
Benjamin Petersond23f8222009-04-05 19:13:16 +0000213 Normalize the case of a pathname. On Unix and Mac OS X, this returns the
214 path unchanged; on case-insensitive filesystems, it converts the path to
215 lowercase. On Windows, it also converts forward slashes to backward slashes.
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +0000216 Raise a TypeError if the type of *path* is not ``str`` or ``bytes``.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218
219.. function:: normpath(path)
220
Terry Jan Reedyec6e1322013-03-17 15:21:26 -0400221 Normalize a pathname by collapsing redundant separators and up-level
222 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
223 become ``A/B``. This string manipulation may change the meaning of a path
224 that contains symbolic links. On Windows, it converts forward slashes to
Terry Jan Reedyf3460412013-03-17 15:28:10 -0400225 backward slashes. To normalize case, use :func:`normcase`.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227
228.. function:: realpath(path)
229
230 Return the canonical path of the specified filename, eliminating any symbolic
231 links encountered in the path (if they are supported by the operating system).
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Georg Brandl18244152009-09-02 20:34:52 +0000234.. function:: relpath(path, start=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236 Return a relative filepath to *path* either from the current directory or from
237 an optional *start* point.
238
Benjamin Petersonf650e462010-05-06 23:03:05 +0000239 *start* defaults to :attr:`os.curdir`.
240
Antoine Pitrouf10f1622010-12-12 20:17:29 +0000241 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244.. function:: samefile(path1, path2)
245
Brian Curtind40e6f72010-07-08 21:39:08 +0000246 Return ``True`` if both pathname arguments refer to the same file or directory.
247 On Unix, this is determined by the device number and i-node number and raises an
248 exception if a :func:`os.stat` call on either pathname fails.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000249
Antoine Pitrouf10f1622010-12-12 20:17:29 +0000250 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Georg Brandlb3823372010-07-10 08:58:37 +0000252 .. versionchanged:: 3.2
253 Added Windows support.
Brian Curtinc7395692010-07-09 15:15:09 +0000254
Brian Curtin490b32a2012-12-26 07:03:03 -0600255 .. versionchanged:: 3.4
256 Windows now uses the same implementation as all other platforms.
257
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259.. function:: sameopenfile(fp1, fp2)
260
261 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000262
Brian Curtin62857742010-09-06 17:07:27 +0000263 Availability: Unix, Windows.
264
Georg Brandl61063cc2012-06-24 22:48:30 +0200265 .. versionchanged:: 3.2
266 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
269.. function:: samestat(stat1, stat2)
270
271 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
272 These structures may have been returned by :func:`fstat`, :func:`lstat`, or
273 :func:`stat`. This function implements the underlying comparison used by
Benjamin Petersonf650e462010-05-06 23:03:05 +0000274 :func:`samefile` and :func:`sameopenfile`.
275
Brian Curtin490b32a2012-12-26 07:03:03 -0600276 Availability: Unix, Windows.
277
278 .. versionchanged:: 3.4
279 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
282.. function:: split(path)
283
Georg Brandl539c1652010-10-14 06:46:08 +0000284 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
285 last pathname component and *head* is everything leading up to that. The
286 *tail* part will never contain a slash; if *path* ends in a slash, *tail*
287 will be empty. If there is no slash in *path*, *head* will be empty. If
288 *path* is empty, both *head* and *tail* are empty. Trailing slashes are
289 stripped from *head* unless it is the root (one or more slashes only). In
290 all cases, ``join(head, tail)`` returns a path to the same location as *path*
Chris Jerdonek0b502ff2012-11-25 20:38:01 -0800291 (but the strings may differ). Also see the functions :func:`dirname` and
292 :func:`basename`.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294
295.. function:: splitdrive(path)
296
297 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
Mark Hammond5a607a32009-05-06 08:04:54 +0000298 a mount point or the empty string. On systems which do not use drive
Georg Brandl116aa622007-08-15 14:28:22 +0000299 specifications, *drive* will always be the empty string. In all cases, ``drive
300 + tail`` will be the same as *path*.
301
Mark Hammond5a607a32009-05-06 08:04:54 +0000302 On Windows, splits a pathname into drive/UNC sharepoint and relative path.
303
304 If the path contains a drive letter, drive will contain everything
305 up to and including the colon.
306 e.g. ``splitdrive("c:/dir")`` returns ``("c:", "/dir")``
307
308 If the path contains a UNC path, drive will contain the host name
309 and share, up to but not including the fourth separator.
310 e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")``
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313.. function:: splitext(path)
314
315 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
316 path``, and *ext* is empty or begins with a period and contains at most one
317 period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
318 returns ``('.cshrc', '')``.
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321.. function:: splitunc(path)
322
Mark Hammond5a607a32009-05-06 08:04:54 +0000323 .. deprecated:: 3.1
324 Use *splitdrive* instead.
325
Georg Brandl116aa622007-08-15 14:28:22 +0000326 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
327 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
328 the path (such as ``r'\path\file.ext'``). For paths containing drive letters,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000329 *unc* will always be the empty string.
330
331 Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334.. data:: supports_unicode_filenames
335
336 True if arbitrary Unicode strings can be used as file names (within limitations
Victor Stinnerb55e4982010-09-11 00:22:12 +0000337 imposed by the file system).