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