blob: 22272a79d40a5b84511a956c5f2108471a7a1e0f [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
Georg Brandl76e55382008-10-08 16:34:57 +000020.. note::
21
22 All of these functions accept either only bytes or only string objects as
23 their parameters. The result is an object of the same type, if a path or
24 file name is returned.
25
Georg Brandl116aa622007-08-15 14:28:22 +000026
Benjamin Petersond23f8222009-04-05 19:13:16 +000027.. note::
28
29 Since different operating systems have different path name conventions, there
30 are several versions of this module in the standard library. The
31 :mod:`os.path` module is always the path module suitable for the operating
32 system Python is running on, and therefore usable for local paths. However,
33 you can also import and use the individual modules if you want to manipulate
34 a path that is *always* in one of the different formats. They all have the
35 same interface:
36
37 * :mod:`posixpath` for UNIX-style paths
38 * :mod:`ntpath` for Windows paths
39 * :mod:`macpath` for old-style MacOS paths
40 * :mod:`os2emxpath` for OS/2 EMX paths
41
42
Georg Brandl116aa622007-08-15 14:28:22 +000043.. function:: abspath(path)
44
45 Return a normalized absolutized version of the pathname *path*. On most
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080046 platforms, this is equivalent to calling the function :func:`normpath` as
47 follows: ``normpath(join(os.getcwd(), path))``.
Georg Brandl116aa622007-08-15 14:28:22 +000048
Georg Brandl116aa622007-08-15 14:28:22 +000049
50.. function:: basename(path)
51
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080052 Return the base name of pathname *path*. This is the second element of the
53 pair returned by passing *path* to the function :func:`split`. Note that
54 the result of this function is different
Georg Brandl116aa622007-08-15 14:28:22 +000055 from the Unix :program:`basename` program; where :program:`basename` for
56 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
57 empty string (``''``).
58
59
60.. function:: commonprefix(list)
61
62 Return the longest path prefix (taken character-by-character) that is a prefix
63 of all paths in *list*. If *list* is empty, return the empty string (``''``).
64 Note that this may return invalid paths because it works a character at a time.
65
66
67.. function:: dirname(path)
68
Chris Jerdonek0b502ff2012-11-25 20:38:01 -080069 Return the directory name of pathname *path*. This is the first element of
70 the pair returned by passing *path* to the function :func:`split`.
Georg Brandl116aa622007-08-15 14:28:22 +000071
72
73.. function:: exists(path)
74
75 Return ``True`` if *path* refers to an existing path. Returns ``False`` for
76 broken symbolic links. On some platforms, this function may return ``False`` if
77 permission is not granted to execute :func:`os.stat` on the requested file, even
78 if the *path* physically exists.
79
80
81.. function:: lexists(path)
82
83 Return ``True`` if *path* refers to an existing path. Returns ``True`` for
84 broken symbolic links. Equivalent to :func:`exists` on platforms lacking
85 :func:`os.lstat`.
86
Georg Brandl116aa622007-08-15 14:28:22 +000087
88.. function:: expanduser(path)
89
90 On Unix and Windows, return the argument with an initial component of ``~`` or
91 ``~user`` replaced by that *user*'s home directory.
92
93 .. index:: module: pwd
94
95 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
96 if it is set; otherwise the current user's home directory is looked up in the
97 password directory through the built-in module :mod:`pwd`. An initial ``~user``
98 is looked up directly in the password directory.
99
100 On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
101 otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
102 used. An initial ``~user`` is handled by stripping the last directory component
103 from the created user path derived above.
104
105 If the expansion fails or if the path does not begin with a tilde, the path is
106 returned unchanged.
107
108
109.. function:: expandvars(path)
110
111 Return the argument with environment variables expanded. Substrings of the form
112 ``$name`` or ``${name}`` are replaced by the value of environment variable
113 *name*. Malformed variable names and references to non-existing variables are
114 left unchanged.
115
116 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
117 ``${name}``.
118
119
120.. function:: getatime(path)
121
122 Return the time of last access of *path*. The return value is a number giving
123 the number of seconds since the epoch (see the :mod:`time` module). Raise
124 :exc:`os.error` if the file does not exist or is inaccessible.
125
Georg Brandl55ac8f02007-09-01 13:51:09 +0000126 If :func:`os.stat_float_times` returns True, the result is a floating point
127 number.
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129
130.. function:: getmtime(path)
131
132 Return the time of last modification of *path*. The return value is a number
133 giving the number of seconds since the epoch (see the :mod:`time` module).
134 Raise :exc:`os.error` if the file does not exist or is inaccessible.
135
Georg Brandl55ac8f02007-09-01 13:51:09 +0000136 If :func:`os.stat_float_times` returns True, the result is a floating point
137 number.
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139
140.. function:: getctime(path)
141
142 Return the system's ctime which, on some systems (like Unix) is the time of the
143 last change, and, on others (like Windows), is the creation time for *path*.
144 The return value is a number giving the number of seconds since the epoch (see
145 the :mod:`time` module). Raise :exc:`os.error` if the file does not exist or
146 is inaccessible.
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149.. function:: getsize(path)
150
151 Return the size, in bytes, of *path*. Raise :exc:`os.error` if the file does
152 not exist or is inaccessible.
153
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155.. function:: isabs(path)
156
Christian Heimesaf98da12008-01-27 15:18:18 +0000157 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
158 begins with a slash, on Windows that it begins with a (back)slash after chopping
159 off a potential drive letter.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161
162.. function:: isfile(path)
163
164 Return ``True`` if *path* is an existing regular file. This follows symbolic
165 links, so both :func:`islink` and :func:`isfile` can be true for the same path.
166
167
168.. function:: isdir(path)
169
170 Return ``True`` if *path* is an existing directory. This follows symbolic
171 links, so both :func:`islink` and :func:`isdir` can be true for the same path.
172
173
174.. function:: islink(path)
175
176 Return ``True`` if *path* refers to a directory entry that is a symbolic link.
177 Always ``False`` if symbolic links are not supported.
178
179
180.. function:: ismount(path)
181
182 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file
183 system where a different file system has been mounted. The function checks
184 whether *path*'s parent, :file:`path/..`, is on a different device than *path*,
185 or whether :file:`path/..` and *path* point to the same i-node on the same
186 device --- this should detect mount points for all Unix and POSIX variants.
187
188
189.. function:: join(path1[, path2[, ...]])
190
191 Join one or more path components intelligently. If any component is an absolute
192 path, all previous components (on Windows, including the previous drive letter,
193 if there was one) are thrown away, and joining continues. The return value is
194 the concatenation of *path1*, and optionally *path2*, etc., with exactly one
R David Murray24eb4bc2011-06-23 21:26:13 -0400195 directory separator (``os.sep``) following each non-empty part except the last.
196 (This means that an empty last part will result in a path that ends with a
197 separator.) Note that on Windows, since there is a current directory for
198 each drive, ``os.path.join("c:", "foo")`` represents a path relative to the
199 current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201
202.. function:: normcase(path)
203
Benjamin Petersond23f8222009-04-05 19:13:16 +0000204 Normalize the case of a pathname. On Unix and Mac OS X, this returns the
205 path unchanged; on case-insensitive filesystems, it converts the path to
206 lowercase. On Windows, it also converts forward slashes to backward slashes.
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +0000207 Raise a TypeError if the type of *path* is not ``str`` or ``bytes``.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
210.. function:: normpath(path)
211
212 Normalize a pathname. This collapses redundant separators and up-level
Georg Brandl353ebce2010-08-02 19:19:26 +0000213 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all become
214 ``A/B``.
215
Georg Brandl116aa622007-08-15 14:28:22 +0000216 It does not normalize the case (use :func:`normcase` for that). On Windows, it
217 converts forward slashes to backward slashes. It should be understood that this
218 may change the meaning of the path if it contains symbolic links!
219
220
221.. function:: realpath(path)
222
223 Return the canonical path of the specified filename, eliminating any symbolic
224 links encountered in the path (if they are supported by the operating system).
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Georg Brandl18244152009-09-02 20:34:52 +0000227.. function:: relpath(path, start=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229 Return a relative filepath to *path* either from the current directory or from
230 an optional *start* point.
231
Benjamin Petersonf650e462010-05-06 23:03:05 +0000232 *start* defaults to :attr:`os.curdir`.
233
Antoine Pitrouf10f1622010-12-12 20:17:29 +0000234 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. function:: samefile(path1, path2)
238
Brian Curtind40e6f72010-07-08 21:39:08 +0000239 Return ``True`` if both pathname arguments refer to the same file or directory.
240 On Unix, this is determined by the device number and i-node number and raises an
241 exception if a :func:`os.stat` call on either pathname fails.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000242
Brian Curtind40e6f72010-07-08 21:39:08 +0000243 On Windows, two files are the same if they resolve to the same final path
Brian Curtinc7395692010-07-09 15:15:09 +0000244 name using the Windows API call GetFinalPathNameByHandle. This function
Brian Curtind40e6f72010-07-08 21:39:08 +0000245 raises an exception if handles cannot be obtained to either file.
246
Antoine Pitrouf10f1622010-12-12 20:17:29 +0000247 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000248
Georg Brandlb3823372010-07-10 08:58:37 +0000249 .. versionchanged:: 3.2
250 Added Windows support.
Brian Curtinc7395692010-07-09 15:15:09 +0000251
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253.. function:: sameopenfile(fp1, fp2)
254
255 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
Benjamin Petersonf650e462010-05-06 23:03:05 +0000256
Brian Curtin62857742010-09-06 17:07:27 +0000257 Availability: Unix, Windows.
258
259 .. versionchanged:: 3.2 Added Windows support.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261
262.. function:: samestat(stat1, stat2)
263
264 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
265 These structures may have been returned by :func:`fstat`, :func:`lstat`, or
266 :func:`stat`. This function implements the underlying comparison used by
Benjamin Petersonf650e462010-05-06 23:03:05 +0000267 :func:`samefile` and :func:`sameopenfile`.
268
269 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271
272.. function:: split(path)
273
Georg Brandl539c1652010-10-14 06:46:08 +0000274 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
275 last pathname component and *head* is everything leading up to that. The
276 *tail* part will never contain a slash; if *path* ends in a slash, *tail*
277 will be empty. If there is no slash in *path*, *head* will be empty. If
278 *path* is empty, both *head* and *tail* are empty. Trailing slashes are
279 stripped from *head* unless it is the root (one or more slashes only). In
280 all cases, ``join(head, tail)`` returns a path to the same location as *path*
Chris Jerdonek0b502ff2012-11-25 20:38:01 -0800281 (but the strings may differ). Also see the functions :func:`dirname` and
282 :func:`basename`.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284
285.. function:: splitdrive(path)
286
287 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
Mark Hammond5a607a32009-05-06 08:04:54 +0000288 a mount point or the empty string. On systems which do not use drive
Georg Brandl116aa622007-08-15 14:28:22 +0000289 specifications, *drive* will always be the empty string. In all cases, ``drive
290 + tail`` will be the same as *path*.
291
Mark Hammond5a607a32009-05-06 08:04:54 +0000292 On Windows, splits a pathname into drive/UNC sharepoint and relative path.
293
294 If the path contains a drive letter, drive will contain everything
295 up to and including the colon.
296 e.g. ``splitdrive("c:/dir")`` returns ``("c:", "/dir")``
297
298 If the path contains a UNC path, drive will contain the host name
299 and share, up to but not including the fourth separator.
300 e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")``
301
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303.. function:: splitext(path)
304
305 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
306 path``, and *ext* is empty or begins with a period and contains at most one
307 period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
308 returns ``('.cshrc', '')``.
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. function:: splitunc(path)
312
Mark Hammond5a607a32009-05-06 08:04:54 +0000313 .. deprecated:: 3.1
314 Use *splitdrive* instead.
315
Georg Brandl116aa622007-08-15 14:28:22 +0000316 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
317 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
318 the path (such as ``r'\path\file.ext'``). For paths containing drive letters,
Benjamin Petersonf650e462010-05-06 23:03:05 +0000319 *unc* will always be the empty string.
320
321 Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324.. data:: supports_unicode_filenames
325
326 True if arbitrary Unicode strings can be used as file names (within limitations
Victor Stinnerb55e4982010-09-11 00:22:12 +0000327 imposed by the file system).