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 stripping the last directory component from the created
179   user path derived above.
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   .. versionchanged:: 3.6
344      Accepts a :term:`path-like object`.
345
346
347.. function:: realpath(path)
348
349   Return the canonical path of the specified filename, eliminating any symbolic
350   links encountered in the path (if they are supported by the operating
351   system).
352
353   .. note::
354      When symbolic link cycles occur, the returned path will be one member of
355      the cycle, but no guarantee is made about which member that will be.
356
357   .. versionchanged:: 3.6
358      Accepts a :term:`path-like object`.
359
360   .. versionchanged:: 3.8
361      Symbolic links and junctions are now resolved on Windows.
362
363
364.. function:: relpath(path, start=os.curdir)
365
366   Return a relative filepath to *path* either from the current directory or
367   from an optional *start* directory.  This is a path computation:  the
368   filesystem is not accessed to confirm the existence or nature of *path* or
369   *start*.  On Windows, :exc:`ValueError` is raised when *path* and *start*
370   are on different drives.
371
372   *start* defaults to :attr:`os.curdir`.
373
374   .. availability:: Unix, Windows.
375
376   .. versionchanged:: 3.6
377      Accepts a :term:`path-like object`.
378
379
380.. function:: samefile(path1, path2)
381
382   Return ``True`` if both pathname arguments refer to the same file or directory.
383   This is determined by the device number and i-node number and raises an
384   exception if an :func:`os.stat` call on either pathname fails.
385
386   .. availability:: Unix, Windows.
387
388   .. versionchanged:: 3.2
389      Added Windows support.
390
391   .. versionchanged:: 3.4
392      Windows now uses the same implementation as all other platforms.
393
394   .. versionchanged:: 3.6
395      Accepts a :term:`path-like object`.
396
397
398.. function:: sameopenfile(fp1, fp2)
399
400   Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
401
402   .. availability:: Unix, Windows.
403
404   .. versionchanged:: 3.2
405      Added Windows support.
406
407   .. versionchanged:: 3.6
408      Accepts a :term:`path-like object`.
409
410
411.. function:: samestat(stat1, stat2)
412
413   Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
414   These structures may have been returned by :func:`os.fstat`,
415   :func:`os.lstat`, or :func:`os.stat`.  This function implements the
416   underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
417
418   .. availability:: Unix, Windows.
419
420   .. versionchanged:: 3.4
421      Added Windows support.
422
423   .. versionchanged:: 3.6
424      Accepts a :term:`path-like object`.
425
426
427.. function:: split(path)
428
429   Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
430   last pathname component and *head* is everything leading up to that.  The
431   *tail* part will never contain a slash; if *path* ends in a slash, *tail*
432   will be empty.  If there is no slash in *path*, *head* will be empty.  If
433   *path* is empty, both *head* and *tail* are empty.  Trailing slashes are
434   stripped from *head* unless it is the root (one or more slashes only).  In
435   all cases, ``join(head, tail)`` returns a path to the same location as *path*
436   (but the strings may differ).  Also see the functions :func:`dirname` and
437   :func:`basename`.
438
439   .. versionchanged:: 3.6
440      Accepts a :term:`path-like object`.
441
442
443.. function:: splitdrive(path)
444
445   Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
446   a mount point or the empty string.  On systems which do not use drive
447   specifications, *drive* will always be the empty string.  In all cases, ``drive
448   + tail`` will be the same as *path*.
449
450   On Windows, splits a pathname into drive/UNC sharepoint and relative path.
451
452   If the path contains a drive letter, drive will contain everything
453   up to and including the colon.
454   e.g. ``splitdrive("c:/dir")`` returns ``("c:", "/dir")``
455
456   If the path contains a UNC path, drive will contain the host name
457   and share, up to but not including the fourth separator.
458   e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")``
459
460   .. versionchanged:: 3.6
461      Accepts a :term:`path-like object`.
462
463
464.. function:: splitext(path)
465
466   Split the pathname *path* into a pair ``(root, ext)``  such that ``root + ext ==
467   path``, and *ext* is empty or begins with a period and contains at most one
468   period. Leading periods on the basename are  ignored; ``splitext('.cshrc')``
469   returns  ``('.cshrc', '')``.
470
471   .. versionchanged:: 3.6
472      Accepts a :term:`path-like object`.
473
474
475.. data:: supports_unicode_filenames
476
477   ``True`` if arbitrary Unicode strings can be used as file names (within limitations
478   imposed by the file system).
479