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) and
8:source:`Lib/ntpath.py` (for Windows NT).
9
10.. index:: single: path; operations
11
12--------------
13
14This module implements some useful functions on pathnames. To read or
15write files see :func:`open`, and for accessing the filesystem see the
16:mod:`os` module. The path parameters can be passed as either strings,
17or bytes. Applications are encouraged to represent file names as
18(Unicode) character strings. Unfortunately, some file names may not be
19representable as strings on Unix, so applications that need to support
20arbitrary file names on Unix should use bytes objects to represent
21path names. Vice versa, using bytes objects cannot represent all file
22names on Windows (in the standard ``mbcs`` encoding), hence Windows
23applications should use string objects to access all files.
24
25Unlike a unix shell, Python does not do any *automatic* path expansions.
26Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
27explicitly when an application desires shell-like path expansion.  (See also
28the :mod:`glob` module.)
29
30
31.. seealso::
32   The :mod:`pathlib` module offers high-level path objects.
33
34
35.. note::
36
37   All of these functions accept either only bytes or only string objects as
38   their parameters.  The result is an object of the same type, if a path or
39   file name is returned.
40
41
42.. note::
43
44   Since different operating systems have different path name conventions, there
45   are several versions of this module in the standard library.  The
46   :mod:`os.path` module is always the path module suitable for the operating
47   system Python is running on, and therefore usable for local paths.  However,
48   you can also import and use the individual modules if you want to manipulate
49   a path that is *always* in one of the different formats.  They all have the
50   same interface:
51
52   * :mod:`posixpath` for UNIX-style paths
53   * :mod:`ntpath` for Windows paths
54
55
56.. versionchanged:: 3.8
57
58   :func:`exists`, :func:`lexists`, :func:`isdir`, :func:`isfile`,
59   :func:`islink`, and :func:`ismount` now return ``False`` instead of
60   raising an exception for paths that contain characters or bytes
61   unrepresentable at the OS level.
62
63
64.. function:: abspath(path)
65
66   Return a normalized absolutized version of the pathname *path*. On most
67   platforms, this is equivalent to calling the function :func:`normpath` as
68   follows: ``normpath(join(os.getcwd(), path))``.
69
70   .. versionchanged:: 3.6
71      Accepts a :term:`path-like object`.
72
73
74.. function:: basename(path)
75
76   Return the base name of pathname *path*.  This is the second element of the
77   pair returned by passing *path* to the function :func:`split`.  Note that
78   the result of this function is different
79   from the Unix :program:`basename` program; where :program:`basename` for
80   ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
81   empty string (``''``).
82
83   .. versionchanged:: 3.6
84      Accepts a :term:`path-like object`.
85
86
87.. function:: commonpath(paths)
88
89   Return the longest common sub-path of each pathname in the sequence
90   *paths*.  Raise :exc:`ValueError` if *paths* contain both absolute
91   and relative pathnames, the *paths* are on the different drives or
92   if *paths* is empty.  Unlike :func:`commonprefix`, this returns a
93   valid path.
94
95   .. availability:: Unix, Windows.
96
97   .. versionadded:: 3.5
98
99   .. versionchanged:: 3.6
100      Accepts a sequence of :term:`path-like objects <path-like object>`.
101
102
103.. function:: commonprefix(list)
104
105   Return the longest path prefix (taken character-by-character) that is a
106   prefix of all paths in  *list*.  If *list* is empty, return the empty string
107   (``''``).
108
109   .. note::
110
111      This function may return invalid paths because it works a
112      character at a time.  To obtain a valid path, see
113      :func:`commonpath`.
114
115      ::
116
117        >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
118        '/usr/l'
119
120        >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
121        '/usr'
122
123   .. versionchanged:: 3.6
124      Accepts a :term:`path-like object`.
125
126
127.. function:: dirname(path)
128
129   Return the directory name of pathname *path*.  This is the first element of
130   the pair returned by passing *path* to the function :func:`split`.
131
132   .. versionchanged:: 3.6
133      Accepts a :term:`path-like object`.
134
135
136.. function:: exists(path)
137
138   Return ``True`` if *path* refers to an existing path or an open
139   file descriptor.  Returns ``False`` for broken symbolic links.  On
140   some platforms, this function may return ``False`` if permission is
141   not granted to execute :func:`os.stat` on the requested file, even
142   if the *path* physically exists.
143
144   .. versionchanged:: 3.3
145      *path* can now be an integer: ``True`` is returned if it is an
146       open file descriptor, ``False`` otherwise.
147
148   .. versionchanged:: 3.6
149      Accepts a :term:`path-like object`.
150
151
152.. function:: lexists(path)
153
154   Return ``True`` if *path* refers to an existing path. Returns ``True`` for
155   broken symbolic links.   Equivalent to :func:`exists` on platforms lacking
156   :func:`os.lstat`.
157
158   .. versionchanged:: 3.6
159      Accepts a :term:`path-like object`.
160
161
162.. index:: single: ~ (tilde); home directory expansion
163
164.. function:: expanduser(path)
165
166   On Unix and Windows, return the argument with an initial component of ``~`` or
167   ``~user`` replaced by that *user*'s home directory.
168
169   .. index:: module: pwd
170
171   On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
172   if it is set; otherwise the current user's home directory is looked up in the
173   password directory through the built-in module :mod:`pwd`. An initial ``~user``
174   is looked up directly in the password directory.
175
176   On Windows, :envvar:`USERPROFILE` will be used if set, otherwise a combination
177   of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be used.  An initial
178   ``~user`` is handled by checking that the last directory component of the current
179   user's home directory matches :envvar:`USERNAME`, and replacing it if so.
180
181   If the expansion fails or if the path does not begin with a tilde, the path is
182   returned unchanged.
183
184   .. versionchanged:: 3.6
185      Accepts a :term:`path-like object`.
186
187   .. versionchanged:: 3.8
188      No longer uses :envvar:`HOME` on Windows.
189
190.. index::
191   single: $ (dollar); environment variables expansion
192   single: % (percent); environment variables expansion (Windows)
193
194.. function:: expandvars(path)
195
196   Return the argument with environment variables expanded.  Substrings of the form
197   ``$name`` or ``${name}`` are replaced by the value of environment variable
198   *name*.  Malformed variable names and references to non-existing variables are
199   left unchanged.
200
201   On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
202   ``${name}``.
203
204   .. versionchanged:: 3.6
205      Accepts a :term:`path-like object`.
206
207
208.. function:: getatime(path)
209
210   Return the time of last access of *path*.  The return value is a floating point number giving
211   the number of seconds since the epoch (see the  :mod:`time` module).  Raise
212   :exc:`OSError` if the file does not exist or is inaccessible.
213
214
215.. function:: getmtime(path)
216
217   Return the time of last modification of *path*.  The return value is a floating point number
218   giving the number of seconds since the epoch (see the  :mod:`time` module).
219   Raise :exc:`OSError` if the file does not exist or is inaccessible.
220
221   .. versionchanged:: 3.6
222      Accepts a :term:`path-like object`.
223
224
225.. function:: getctime(path)
226
227   Return the system's ctime which, on some systems (like Unix) is the time of the
228   last metadata change, and, on others (like Windows), is the creation time for *path*.
229   The return value is a number giving the number of seconds since the epoch (see
230   the  :mod:`time` module).  Raise :exc:`OSError` if the file does not exist or
231   is inaccessible.
232
233   .. versionchanged:: 3.6
234      Accepts a :term:`path-like object`.
235
236
237.. function:: getsize(path)
238
239   Return the size, in bytes, of *path*.  Raise :exc:`OSError` if the file does
240   not exist or is inaccessible.
241
242   .. versionchanged:: 3.6
243      Accepts a :term:`path-like object`.
244
245
246.. function:: isabs(path)
247
248   Return ``True`` if *path* is an absolute pathname.  On Unix, that means it
249   begins with a slash, on Windows that it begins with a (back)slash after chopping
250   off a potential drive letter.
251
252   .. versionchanged:: 3.6
253      Accepts a :term:`path-like object`.
254
255
256.. function:: isfile(path)
257
258   Return ``True`` if *path* is an :func:`existing <exists>` regular file.
259   This follows symbolic links, so both :func:`islink` and :func:`isfile` can
260   be true for the same path.
261
262   .. versionchanged:: 3.6
263      Accepts a :term:`path-like object`.
264
265
266.. function:: isdir(path)
267
268   Return ``True`` if *path* is an :func:`existing <exists>` directory.  This
269   follows symbolic links, so both :func:`islink` and :func:`isdir` can be true
270   for the same path.
271
272   .. versionchanged:: 3.6
273      Accepts a :term:`path-like object`.
274
275
276.. function:: islink(path)
277
278   Return ``True`` if *path* refers to an :func:`existing <exists>` directory
279   entry that is a symbolic link.  Always ``False`` if symbolic links are not
280   supported by the Python runtime.
281
282   .. versionchanged:: 3.6
283      Accepts a :term:`path-like object`.
284
285
286.. function:: ismount(path)
287
288   Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a
289   file system where a different file system has been mounted.  On POSIX, the
290   function checks whether *path*'s parent, :file:`{path}/..`, is on a different
291   device than *path*, or whether :file:`{path}/..` and *path* point to the same
292   i-node on the same device --- this should detect mount points for all Unix
293   and POSIX variants.  It is not able to reliably detect bind mounts on the
294   same filesystem.  On Windows, a drive letter root and a share UNC are
295   always mount points, and for any other path ``GetVolumePathName`` is called
296   to see if it is different from the input path.
297
298   .. versionadded:: 3.4
299      Support for detecting non-root mount points on Windows.
300
301   .. versionchanged:: 3.6
302      Accepts a :term:`path-like object`.
303
304
305.. function:: join(path, *paths)
306
307   Join one or more path components intelligently.  The return value is the
308   concatenation of *path* and any members of *\*paths* with exactly one
309   directory separator following each non-empty part except the last, meaning
310   that the result will only end in a separator if the last part is empty.  If
311   a component is an absolute path, all previous components are thrown away
312   and joining continues from the absolute path component.
313
314   On Windows, the drive letter is not reset when an absolute path component
315   (e.g., ``r'\foo'``) is encountered.  If a component contains a drive
316   letter, all previous components are thrown away and the drive letter is
317   reset.  Note that since there is a current directory for each drive,
318   ``os.path.join("c:", "foo")`` represents a path relative to the current
319   directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
320
321   .. versionchanged:: 3.6
322      Accepts a :term:`path-like object` for *path* and *paths*.
323
324
325.. function:: normcase(path)
326
327   Normalize the case of a pathname.  On Windows, convert all characters in the
328   pathname to lowercase, and also convert forward slashes to backward slashes.
329   On other operating systems, return the path unchanged.
330
331   .. versionchanged:: 3.6
332      Accepts a :term:`path-like object`.
333
334
335.. function:: normpath(path)
336
337   Normalize a pathname by collapsing redundant separators and up-level
338   references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
339   become ``A/B``.  This string manipulation may change the meaning of a path
340   that contains symbolic links.  On Windows, it converts forward slashes to
341   backward slashes. To normalize case, use :func:`normcase`.
342
343  .. note::
344      On POSIX systems, in accordance with `IEEE Std 1003.1 2013 Edition; 4.13
345      Pathname Resolution <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>`_,
346      if a pathname begins with exactly two slashes, the first component
347      following the leading characters may be interpreted in an implementation-defined
348      manner, although more than two leading characters shall be treated as a
349      single character.
350
351   .. versionchanged:: 3.6
352      Accepts a :term:`path-like object`.
353
354
355.. function:: realpath(path, *, strict=False)
356
357   Return the canonical path of the specified filename, eliminating any symbolic
358   links encountered in the path (if they are supported by the operating
359   system).
360
361   If a path doesn't exist or a symlink loop is encountered, and *strict* is
362   ``True``, :exc:`OSError` is raised. If *strict* is ``False``, the path is
363   resolved as far as possible and any remainder is appended without checking
364   whether it exists.
365
366   .. note::
367      This function emulates the operating system's procedure for making a path
368      canonical, which differs slightly between Windows and UNIX with respect
369      to how links and subsequent path components interact.
370
371      Operating system APIs make paths canonical as needed, so it's not
372      normally necessary to call this function.
373
374   .. versionchanged:: 3.6
375      Accepts a :term:`path-like object`.
376
377   .. versionchanged:: 3.8
378      Symbolic links and junctions are now resolved on Windows.
379
380   .. versionchanged:: 3.10
381      The *strict* parameter was added.
382
383
384.. function:: relpath(path, start=os.curdir)
385
386   Return a relative filepath to *path* either from the current directory or
387   from an optional *start* directory.  This is a path computation:  the
388   filesystem is not accessed to confirm the existence or nature of *path* or
389   *start*.  On Windows, :exc:`ValueError` is raised when *path* and *start*
390   are on different drives.
391
392   *start* defaults to :attr:`os.curdir`.
393
394   .. availability:: Unix, Windows.
395
396   .. versionchanged:: 3.6
397      Accepts a :term:`path-like object`.
398
399
400.. function:: samefile(path1, path2)
401
402   Return ``True`` if both pathname arguments refer to the same file or directory.
403   This is determined by the device number and i-node number and raises an
404   exception if an :func:`os.stat` call on either pathname fails.
405
406   .. availability:: Unix, Windows.
407
408   .. versionchanged:: 3.2
409      Added Windows support.
410
411   .. versionchanged:: 3.4
412      Windows now uses the same implementation as all other platforms.
413
414   .. versionchanged:: 3.6
415      Accepts a :term:`path-like object`.
416
417
418.. function:: sameopenfile(fp1, fp2)
419
420   Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
421
422   .. availability:: Unix, Windows.
423
424   .. versionchanged:: 3.2
425      Added Windows support.
426
427   .. versionchanged:: 3.6
428      Accepts a :term:`path-like object`.
429
430
431.. function:: samestat(stat1, stat2)
432
433   Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
434   These structures may have been returned by :func:`os.fstat`,
435   :func:`os.lstat`, or :func:`os.stat`.  This function implements the
436   underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
437
438   .. availability:: Unix, Windows.
439
440   .. versionchanged:: 3.4
441      Added Windows support.
442
443   .. versionchanged:: 3.6
444      Accepts a :term:`path-like object`.
445
446
447.. function:: split(path)
448
449   Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
450   last pathname component and *head* is everything leading up to that.  The
451   *tail* part will never contain a slash; if *path* ends in a slash, *tail*
452   will be empty.  If there is no slash in *path*, *head* will be empty.  If
453   *path* is empty, both *head* and *tail* are empty.  Trailing slashes are
454   stripped from *head* unless it is the root (one or more slashes only).  In
455   all cases, ``join(head, tail)`` returns a path to the same location as *path*
456   (but the strings may differ).  Also see the functions :func:`dirname` and
457   :func:`basename`.
458
459   .. versionchanged:: 3.6
460      Accepts a :term:`path-like object`.
461
462
463.. function:: splitdrive(path)
464
465   Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
466   a mount point or the empty string.  On systems which do not use drive
467   specifications, *drive* will always be the empty string.  In all cases, ``drive
468   + tail`` will be the same as *path*.
469
470   On Windows, splits a pathname into drive/UNC sharepoint and relative path.
471
472   If the path contains a drive letter, drive will contain everything
473   up to and including the colon::
474
475      >>> splitdrive("c:/dir")
476      ("c:", "/dir")
477
478   If the path contains a UNC path, drive will contain the host name
479   and share, up to but not including the fourth separator::
480
481      >>> splitdrive("//host/computer/dir")
482      ("//host/computer", "/dir")
483
484   .. versionchanged:: 3.6
485      Accepts a :term:`path-like object`.
486
487
488.. function:: splitext(path)
489
490   Split the pathname *path* into a pair ``(root, ext)``  such that ``root + ext ==
491   path``, and the extension, *ext*, is empty or begins with a period and contains at
492   most one period.
493
494   If the path contains no extension, *ext* will be ``''``::
495
496      >>> splitext('bar')
497      ('bar', '')
498
499   If the path contains an extension, then *ext* will be set to this extension,
500   including the leading period. Note that previous periods will be ignored::
501
502      >>> splitext('foo.bar.exe')
503      ('foo.bar', '.exe')
504
505   Leading periods on the basename are ignored::
506
507      >>> splitext('.cshrc')
508      ('.cshrc', '')
509
510   .. versionchanged:: 3.6
511      Accepts a :term:`path-like object`.
512
513
514.. data:: supports_unicode_filenames
515
516   ``True`` if arbitrary Unicode strings can be used as file names (within limitations
517   imposed by the file system).
518