1:mod:`os.path` --- Common pathname manipulations
2================================================
3
4.. module:: os.path
5   :synopsis: Operations on pathnames.
6
7**Source code:** :source:`Lib/posixpath.py` (for POSIX),
8:source:`Lib/ntpath.py` (for Windows NT),
9and :source:`Lib/macpath.py` (for Macintosh)
10
11.. index:: single: path; operations
12
13--------------
14
15This module implements some useful functions on pathnames. To read or
16write files see :func:`open`, and for accessing the filesystem see the
17: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.
25
26Unlike 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
31
32.. seealso::
33   The :mod:`pathlib` module offers high-level path objects.
34
35
36.. 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
42
43.. 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
56
57
58.. function:: abspath(path)
59
60   Return a normalized absolutized version of the pathname *path*. On most
61   platforms, this is equivalent to calling the function :func:`normpath` as
62   follows: ``normpath(join(os.getcwd(), path))``.
63
64   .. versionchanged:: 3.6
65      Accepts a :term:`path-like object`.
66
67
68.. function:: basename(path)
69
70   Return the base name of pathname *path*.  This is the second element of the
71   pair returned by passing *path* to the function :func:`split`.  Note that
72   the result of this function is different
73   from the Unix :program:`basename` program; where :program:`basename` for
74   ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
75   empty string (``''``).
76
77   .. versionchanged:: 3.6
78      Accepts a :term:`path-like object`.
79
80
81.. function:: commonpath(paths)
82
83   Return the longest common sub-path of each pathname in the sequence
84   *paths*.  Raise ValueError if *paths* contains both absolute and relative
85   pathnames, or if *paths* is empty.  Unlike :func:`commonprefix`, this
86   returns a valid path.
87
88   Availability: Unix, Windows
89
90   .. versionadded:: 3.5
91
92   .. versionchanged:: 3.6
93      Accepts a sequence of :term:`path-like objects <path-like object>`.
94
95
96.. function:: commonprefix(list)
97
98   Return the longest path prefix (taken character-by-character) that is a
99   prefix of all paths in  *list*.  If *list* is empty, return the empty string
100   (``''``).
101
102   .. note::
103
104      This function may return invalid paths because it works a
105      character at a time.  To obtain a valid path, see
106      :func:`commonpath`.
107
108      ::
109
110        >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
111        '/usr/l'
112
113        >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
114        '/usr'
115
116   .. versionchanged:: 3.6
117      Accepts a :term:`path-like object`.
118
119
120.. function:: dirname(path)
121
122   Return the directory name of pathname *path*.  This is the first element of
123   the pair returned by passing *path* to the function :func:`split`.
124
125   .. versionchanged:: 3.6
126      Accepts a :term:`path-like object`.
127
128
129.. function:: exists(path)
130
131   Return ``True`` if *path* refers to an existing path or an open
132   file descriptor.  Returns ``False`` for broken symbolic links.  On
133   some platforms, this function may return ``False`` if permission is
134   not granted to execute :func:`os.stat` on the requested file, even
135   if the *path* physically exists.
136
137   .. versionchanged:: 3.3
138      *path* can now be an integer: ``True`` is returned if it is an
139       open file descriptor, ``False`` otherwise.
140
141   .. versionchanged:: 3.6
142      Accepts a :term:`path-like object`.
143
144
145.. function:: lexists(path)
146
147   Return ``True`` if *path* refers to an existing path. Returns ``True`` for
148   broken symbolic links.   Equivalent to :func:`exists` on platforms lacking
149   :func:`os.lstat`.
150
151   .. versionchanged:: 3.6
152      Accepts a :term:`path-like object`.
153
154
155.. function:: expanduser(path)
156
157   On Unix and Windows, return the argument with an initial component of ``~`` or
158   ``~user`` replaced by that *user*'s home directory.
159
160   .. index:: module: pwd
161
162   On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
163   if it is set; otherwise the current user's home directory is looked up in the
164   password directory through the built-in module :mod:`pwd`. An initial ``~user``
165   is looked up directly in the password directory.
166
167   On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
168   otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
169   used.  An initial ``~user`` is handled by stripping the last directory component
170   from the created user path derived above.
171
172   If the expansion fails or if the path does not begin with a tilde, the path is
173   returned unchanged.
174
175   .. versionchanged:: 3.6
176      Accepts a :term:`path-like object`.
177
178
179.. function:: expandvars(path)
180
181   Return the argument with environment variables expanded.  Substrings of the form
182   ``$name`` or ``${name}`` are replaced by the value of environment variable
183   *name*.  Malformed variable names and references to non-existing variables are
184   left unchanged.
185
186   On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
187   ``${name}``.
188
189   .. versionchanged:: 3.6
190      Accepts a :term:`path-like object`.
191
192
193.. function:: getatime(path)
194
195   Return the time of last access of *path*.  The return value is a number giving
196   the number of seconds since the epoch (see the  :mod:`time` module).  Raise
197   :exc:`OSError` if the file does not exist or is inaccessible.
198
199   If :func:`os.stat_float_times` returns ``True``, the result is a floating point
200   number.
201
202
203.. function:: getmtime(path)
204
205   Return the time of last modification of *path*.  The return value is a number
206   giving the number of seconds since the epoch (see the  :mod:`time` module).
207   Raise :exc:`OSError` if the file does not exist or is inaccessible.
208
209   If :func:`os.stat_float_times` returns ``True``, the result is a floating point
210   number.
211
212   .. versionchanged:: 3.6
213      Accepts a :term:`path-like object`.
214
215
216.. function:: getctime(path)
217
218   Return the system's ctime which, on some systems (like Unix) is the time of the
219   last metadata change, and, on others (like Windows), is the creation time for *path*.
220   The return value is a number giving the number of seconds since the epoch (see
221   the  :mod:`time` module).  Raise :exc:`OSError` if the file does not exist or
222   is inaccessible.
223
224   .. versionchanged:: 3.6
225      Accepts a :term:`path-like object`.
226
227
228.. function:: getsize(path)
229
230   Return the size, in bytes, of *path*.  Raise :exc:`OSError` if the file does
231   not exist or is inaccessible.
232
233   .. versionchanged:: 3.6
234      Accepts a :term:`path-like object`.
235
236
237.. function:: isabs(path)
238
239   Return ``True`` if *path* is an absolute pathname.  On Unix, that means it
240   begins with a slash, on Windows that it begins with a (back)slash after chopping
241   off a potential drive letter.
242
243   .. versionchanged:: 3.6
244      Accepts a :term:`path-like object`.
245
246
247.. function:: isfile(path)
248
249   Return ``True`` if *path* is an existing regular file.  This follows symbolic
250   links, so both :func:`islink` and :func:`isfile` can be true for the same path.
251
252   .. versionchanged:: 3.6
253      Accepts a :term:`path-like object`.
254
255
256.. function:: isdir(path)
257
258   Return ``True`` if *path* is an existing directory.  This follows symbolic
259   links, so both :func:`islink` and :func:`isdir` can be true for the same path.
260
261   .. versionchanged:: 3.6
262      Accepts a :term:`path-like object`.
263
264
265.. function:: islink(path)
266
267   Return ``True`` if *path* refers to a directory entry that is a symbolic link.
268   Always ``False`` if symbolic links are not supported by the Python runtime.
269
270   .. versionchanged:: 3.6
271      Accepts a :term:`path-like object`.
272
273
274.. function:: ismount(path)
275
276   Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a
277   file system where a different file system has been mounted.  On POSIX, the
278   function checks whether *path*'s parent, :file:`path/..`, is on a different
279   device than *path*, or whether :file:`path/..` and *path* point to the same
280   i-node on the same device --- this should detect mount points for all Unix
281   and POSIX variants.  On Windows, a drive letter root and a share UNC are
282   always mount points, and for any other path ``GetVolumePathName`` is called
283   to see if it is different from the input path.
284
285   .. versionadded:: 3.4
286      Support for detecting non-root mount points on Windows.
287
288   .. versionchanged:: 3.6
289      Accepts a :term:`path-like object`.
290
291
292.. function:: join(path, *paths)
293
294   Join one or more path components intelligently.  The return value is the
295   concatenation of *path* and any members of *\*paths* with exactly one
296   directory separator (``os.sep``) following each non-empty part except the
297   last, meaning that the result will only end in a separator if the last
298   part is empty.  If a component is an absolute path, all previous
299   components are thrown away and joining continues from the absolute path
300   component.
301
302   On Windows, the drive letter is not reset when an absolute path component
303   (e.g., ``r'\foo'``) is encountered.  If a component contains a drive
304   letter, all previous components are thrown away and the drive letter is
305   reset.  Note that since there is a current directory for each drive,
306   ``os.path.join("c:", "foo")`` represents a path relative to the current
307   directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
308
309   .. versionchanged:: 3.6
310      Accepts a :term:`path-like object` for *path* and *paths*.
311
312
313.. function:: normcase(path)
314
315   Normalize the case of a pathname.  On Unix and Mac OS X, this returns the
316   path unchanged; on case-insensitive filesystems, it converts the path to
317   lowercase.  On Windows, it also converts forward slashes to backward slashes.
318   Raise a TypeError if the type of *path* is not ``str`` or ``bytes`` (directly
319   or indirectly through the :class:`os.PathLike` interface).
320
321   .. versionchanged:: 3.6
322      Accepts a :term:`path-like object`.
323
324
325.. function:: normpath(path)
326
327   Normalize a pathname by collapsing redundant separators and up-level
328   references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
329   become ``A/B``.  This string manipulation may change the meaning of a path
330   that contains symbolic links.  On Windows, it converts forward slashes to
331   backward slashes. To normalize case, use :func:`normcase`.
332
333   .. versionchanged:: 3.6
334      Accepts a :term:`path-like object`.
335
336
337.. function:: realpath(path)
338
339   Return the canonical path of the specified filename, eliminating any symbolic
340   links encountered in the path (if they are supported by the operating system).
341
342   .. versionchanged:: 3.6
343      Accepts a :term:`path-like object`.
344
345
346.. function:: relpath(path, start=os.curdir)
347
348   Return a relative filepath to *path* either from the current directory or
349   from an optional *start* directory.  This is a path computation:  the
350   filesystem is not accessed to confirm the existence or nature of *path* or
351   *start*.
352
353   *start* defaults to :attr:`os.curdir`.
354
355   Availability: Unix, Windows.
356
357   .. versionchanged:: 3.6
358      Accepts a :term:`path-like object`.
359
360
361.. function:: samefile(path1, path2)
362
363   Return ``True`` if both pathname arguments refer to the same file or directory.
364   This is determined by the device number and i-node number and raises an
365   exception if an :func:`os.stat` call on either pathname fails.
366
367   Availability: Unix, Windows.
368
369   .. versionchanged:: 3.2
370      Added Windows support.
371
372   .. versionchanged:: 3.4
373      Windows now uses the same implementation as all other platforms.
374
375   .. versionchanged:: 3.6
376      Accepts a :term:`path-like object`.
377
378
379.. function:: sameopenfile(fp1, fp2)
380
381   Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
382
383   Availability: Unix, Windows.
384
385   .. versionchanged:: 3.2
386      Added Windows support.
387
388   .. versionchanged:: 3.6
389      Accepts a :term:`path-like object`.
390
391
392.. function:: samestat(stat1, stat2)
393
394   Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
395   These structures may have been returned by :func:`os.fstat`,
396   :func:`os.lstat`, or :func:`os.stat`.  This function implements the
397   underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
398
399   Availability: Unix, Windows.
400
401   .. versionchanged:: 3.4
402      Added Windows support.
403
404   .. versionchanged:: 3.6
405      Accepts a :term:`path-like object`.
406
407
408.. function:: split(path)
409
410   Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
411   last pathname component and *head* is everything leading up to that.  The
412   *tail* part will never contain a slash; if *path* ends in a slash, *tail*
413   will be empty.  If there is no slash in *path*, *head* will be empty.  If
414   *path* is empty, both *head* and *tail* are empty.  Trailing slashes are
415   stripped from *head* unless it is the root (one or more slashes only).  In
416   all cases, ``join(head, tail)`` returns a path to the same location as *path*
417   (but the strings may differ).  Also see the functions :func:`dirname` and
418   :func:`basename`.
419
420   .. versionchanged:: 3.6
421      Accepts a :term:`path-like object`.
422
423
424.. function:: splitdrive(path)
425
426   Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
427   a mount point or the empty string.  On systems which do not use drive
428   specifications, *drive* will always be the empty string.  In all cases, ``drive
429   + tail`` will be the same as *path*.
430
431   On Windows, splits a pathname into drive/UNC sharepoint and relative path.
432
433   If the path contains a drive letter, drive will contain everything
434   up to and including the colon.
435   e.g. ``splitdrive("c:/dir")`` returns ``("c:", "/dir")``
436
437   If the path contains a UNC path, drive will contain the host name
438   and share, up to but not including the fourth separator.
439   e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")``
440
441   .. versionchanged:: 3.6
442      Accepts a :term:`path-like object`.
443
444
445.. function:: splitext(path)
446
447   Split the pathname *path* into a pair ``(root, ext)``  such that ``root + ext ==
448   path``, and *ext* is empty or begins with a period and contains at most one
449   period. Leading periods on the basename are  ignored; ``splitext('.cshrc')``
450   returns  ``('.cshrc', '')``.
451
452   .. versionchanged:: 3.6
453      Accepts a :term:`path-like object`.
454
455
456.. function:: splitunc(path)
457
458   .. deprecated:: 3.1
459      Use *splitdrive* instead.
460
461   Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
462   mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
463   the path (such as  ``r'\path\file.ext'``).  For paths containing drive letters,
464   *unc* will always be the empty string.
465
466   Availability:  Windows.
467
468
469.. data:: supports_unicode_filenames
470
471   ``True`` if arbitrary Unicode strings can be used as file names (within limitations
472   imposed by the file system).
473