os.path — Common pathname manipulations¶
Source code:Lib/genericpath.py,Lib/posixpath.py (for POSIX) andLib/ntpath.py (for Windows).
This module implements some useful functions on pathnames. To read or writefiles seeopen(), and for accessing the filesystem see theosmodule. The path parameters can be passed as strings, or bytes, or any objectimplementing theos.PathLike protocol.
Unlike a Unix shell, Python does not do anyautomatic path expansions.Functions such asexpanduser() andexpandvars() can be invokedexplicitly when an application desires shell-like path expansion. (See alsotheglob module.)
See also
Thepathlib module offers high-level path objects.
Note
All of these functions accept either only bytes or only string objects astheir parameters. The result is an object of the same type, if a path orfile name is returned.
Note
Since different operating systems have different path name conventions, thereare several versions of this module in the standard library. Theos.path module is always the path module suitable for the operatingsystem Python is running on, and therefore usable for local paths. However,you can also import and use the individual modules if you want to manipulatea path that isalways in one of the different formats. They all have thesame interface:
posixpathfor UNIX-style pathsntpathfor Windows paths
Changed in version 3.8:exists(),lexists(),isdir(),isfile(),islink(), andismount() now returnFalse instead ofraising an exception for paths that contain characters or bytesunrepresentable at the OS level.
- os.path.abspath(path)¶
Return a normalized absolutized version of the pathnamepath. On mostplatforms, this is equivalent to calling the function
normpath()asfollows:normpath(join(os.getcwd(),path)).Changed in version 3.6:Accepts apath-like object.
- os.path.basename(path,/)¶
Return the base name of pathnamepath. This is the second element of thepair returned by passingpath to the function
split(). Note thatthe result of this function is differentfrom the Unixbasename program; wherebasename for'/foo/bar/'returns'bar', thebasename()function returns anempty string ('').Changed in version 3.6:Accepts apath-like object.
- os.path.commonpath(paths)¶
Return the longest common sub-path of each pathname in the iterablepaths. Raise
ValueErrorifpaths contain both absoluteand relative pathnames, ifpaths are on different drives, orifpaths is empty. Unlikecommonprefix(), this returns avalid path.Added in version 3.5.
Changed in version 3.6:Accepts a sequence ofpath-like objects.
Changed in version 3.13:Any iterable can now be passed, rather than just sequences.
- os.path.commonprefix(list,/)¶
Return the longest path prefix (taken character-by-character) that is aprefix of all paths inlist. Iflist is empty, return the empty string(
'').Note
This function may return invalid paths because it works acharacter at a time. To obtain a valid path, see
commonpath().>>>os.path.commonprefix(['/usr/lib','/usr/local/lib'])'/usr/l'>>>os.path.commonpath(['/usr/lib','/usr/local/lib'])'/usr'
Changed in version 3.6:Accepts apath-like object.
- os.path.dirname(path,/)¶
Return the directory name of pathnamepath. This is the first element ofthe pair returned by passingpath to the function
split().Changed in version 3.6:Accepts apath-like object.
- os.path.exists(path)¶
Return
Trueifpath refers to an existing path or an openfile descriptor. ReturnsFalsefor broken symbolic links. Onsome platforms, this function may returnFalseif permission isnot granted to executeos.stat()on the requested file, evenif thepath physically exists.Changed in version 3.3:path can now be an integer:
Trueis returned if it is an open file descriptor,Falseotherwise.Changed in version 3.6:Accepts apath-like object.
- os.path.lexists(path)¶
Return
Trueifpath refers to an existing path, includingbroken symbolic links. Equivalent toexists()on platforms lackingos.lstat().Changed in version 3.6:Accepts apath-like object.
- os.path.expanduser(path)¶
On Unix and Windows, return the argument with an initial component of
~or~userreplaced by thatuser’s home directory.On Unix, an initial
~is replaced by the environment variableHOMEif it is set; otherwise the current user’s home directory is looked up in thepassword directory through the built-in modulepwd. An initial~useris looked up directly in the password directory.On Windows,
USERPROFILEwill be used if set, otherwise a combinationofHOMEPATHandHOMEDRIVEwill be used. An initial~useris handled by checking that the last directory component of the currentuser’s home directory matchesUSERNAME, and replacing it if so.If the expansion fails or if the path does not begin with a tilde, the path isreturned unchanged.
Changed in version 3.6:Accepts apath-like object.
Changed in version 3.8:No longer uses
HOMEon Windows.
- os.path.expandvars(path)¶
Return the argument with environment variables expanded. Substrings of the form
$nameor${name}are replaced by the value of environment variablename. Malformed variable names and references to non-existing variables areleft unchanged.On Windows,
%name%expansions are supported in addition to$nameand${name}.Changed in version 3.6:Accepts apath-like object.
- os.path.getatime(path,/)¶
Return the time of last access ofpath. The return value is a floating-point number givingthe number of seconds since the epoch (see the
timemodule). RaiseOSErrorif the file does not exist or is inaccessible.
- os.path.getmtime(path,/)¶
Return the time of last modification ofpath. The return value is a floating-point numbergiving the number of seconds since the epoch (see the
timemodule).RaiseOSErrorif the file does not exist or is inaccessible.Changed in version 3.6:Accepts apath-like object.
- os.path.getctime(path,/)¶
Return the system’s ctime which, on some systems (like Unix) is the time of thelast metadata change, and, on others (like Windows), is the creation time forpath.The return value is a number giving the number of seconds since the epoch (seethe
timemodule). RaiseOSErrorif the file does not exist oris inaccessible.Changed in version 3.6:Accepts apath-like object.
- os.path.getsize(path,/)¶
Return the size, in bytes, ofpath. Raise
OSErrorif the file doesnot exist or is inaccessible.Changed in version 3.6:Accepts apath-like object.
- os.path.isabs(path,/)¶
Return
Trueifpath is an absolute pathname. On Unix, that means itbegins with a slash, on Windows that it begins with two (back)slashes, or adrive letter, colon, and (back)slash together.Changed in version 3.6:Accepts apath-like object.
Changed in version 3.13:On Windows, returns
Falseif the given path starts with exactly one(back)slash.
- os.path.isfile(path)¶
Return
Trueifpath is anexistingregular file.This follows symbolic links, so bothislink()andisfile()canbe true for the same path.Changed in version 3.6:Accepts apath-like object.
- os.path.isdir(path,/)¶
Return
Trueifpath is anexistingdirectory. Thisfollows symbolic links, so bothislink()andisdir()can be truefor the same path.Changed in version 3.6:Accepts apath-like object.
- os.path.isjunction(path)¶
Return
Trueifpath refers to anexistingdirectoryentry that is a junction. Always returnFalseif junctions are notsupported on the current platform.Added in version 3.12.
- os.path.islink(path)¶
Return
Trueifpath refers to anexistingdirectoryentry that is a symbolic link. AlwaysFalseif symbolic links are notsupported by the Python runtime.Changed in version 3.6:Accepts apath-like object.
- os.path.ismount(path)¶
Return
Trueif pathnamepath is amount point: a point in afile system where a different file system has been mounted. On POSIX, thefunction checks whetherpath’s parent,path/.., is on a differentdevice thanpath, or whetherpath/..andpath point to the samei-node on the same device — this should detect mount points for all Unixand POSIX variants. It is not able to reliably detect bind mounts on thesame filesystem. On Linux systems, it will always returnTruefor btrfssubvolumes, even if they aren’t mount points. On Windows, a drive letter rootand a share UNC are always mount points, and for any other pathGetVolumePathNameis called to see if it is different from the input path.Changed in version 3.4:Added support for detecting non-root mount points on Windows.
Changed in version 3.6:Accepts apath-like object.
- os.path.isdevdrive(path)¶
Return
Trueif pathnamepath is located on a Windows Dev Drive.A Dev Drive is optimized for developer scenarios, and offers fasterperformance for reading and writing files. It is recommended for use forsource code, temporary build directories, package caches, and otherIO-intensive operations.May raise an error for an invalid path, for example, one without arecognizable drive, but returns
Falseon platforms that do not supportDev Drives. Seethe Windows documentationfor information on enabling and creating Dev Drives.Added in version 3.12.
Changed in version 3.13:The function is now available on all platforms, and will always return
Falseon those that have no support for Dev Drives
- os.path.isreserved(path)¶
Return
Trueifpath is a reserved pathname on the current system.On Windows, reserved filenames include those that end with a space or dot;those that contain colons (i.e. file streams such as “name:stream”),wildcard characters (i.e.
'*?"<>'), pipe, or ASCII control characters;as well as DOS device names such as “NUL”, “CON”, “CONIN$”, “CONOUT$”,“AUX”, “PRN”, “COM1”, and “LPT1”.Note
This function approximates rules for reserved paths on most Windowssystems. These rules change over time in various Windows releases.This function may be updated in future Python releases as changes tothe rules become broadly available.
Availability: Windows.
Added in version 3.13.
- os.path.join(path,/,*paths)¶
Join one or more path segments intelligently. The return value is theconcatenation ofpath and all members of*paths, with exactly onedirectory separator following each non-empty part, except the last. That is,the result will only end in a separator if the last part is either empty orends in a separator. If a segment is an absolute path (which on Windowsrequires both a drive and a root), then all previous segments are ignored andjoining continues from the absolute path segment.
On Windows, the drive is not reset when a rooted path segment (e.g.,
r'\foo') is encountered. If a segment is on a different drive or is anabsolute path, all previous segments are ignored and the drive is reset. Notethat since there is a current directory for each drive,os.path.join("c:","foo")represents a path relative to the currentdirectory on driveC:(c:foo), notc:\foo.Changed in version 3.6:Accepts apath-like object forpath andpaths.
- os.path.normcase(path,/)¶
Normalize the case of a pathname. On Windows, convert all characters in thepathname to lowercase, and also convert forward slashes to backward slashes.On other operating systems, return the path unchanged.
Changed in version 3.6:Accepts apath-like object.
- os.path.normpath(path)¶
Normalize a pathname by collapsing redundant separators and up-levelreferences so that
A//B,A/B/,A/./BandA/foo/../BallbecomeA/B. This string manipulation may change the meaning of a paththat contains symbolic links. On Windows, it converts forward slashes tobackward slashes. To normalize case, usenormcase().Note
On POSIX systems, in accordance withIEEE Std 1003.1 2013 Edition; 4.13Pathname Resolution,if a pathname begins with exactly two slashes, the first componentfollowing the leading characters may be interpreted in an implementation-definedmanner, although more than two leading characters shall be treated as asingle character.
Changed in version 3.6:Accepts apath-like object.
- os.path.realpath(path,/,*,strict=False)¶
Return the canonical path of the specified filename, eliminating any symboliclinks encountered in the path (if they are supported by the operatingsystem). On Windows, this function will also resolve MS-DOS (also called 8.3)style names such as
C:\\PROGRA~1toC:\\ProgramFiles.By default, the path is evaluated up to the first component that does notexist, is a symlink loop, or whose evaluation raises
OSError.All such components are appended unchanged to the existing part of the path.Some errors that are handled this way include “access denied”, “not adirectory”, or “bad argument to internal function”. Thus, theresulting path may be missing or inaccessible, may still containlinks or loops, and may traverse non-directories.
This behavior can be modified by keyword arguments:
Ifstrict is
True, the first error encountered when evaluating the path isre-raised.In particular,FileNotFoundErroris raised ifpath does not exist,or anotherOSErrorif it is otherwise inaccessible.Ifstrict is
os.path.ALLOW_MISSING, errors other thanFileNotFoundErrorare re-raised (as withstrict=True).Thus, the returned path will not contain any symbolic links, but the namedfile and some of its parent directories may be missing.Note
This function emulates the operating system’s procedure for making a pathcanonical, which differs slightly between Windows and UNIX with respectto how links and subsequent path components interact.
Operating system APIs make paths canonical as needed, so it’s notnormally necessary to call this function.
Changed in version 3.6:Accepts apath-like object.
Changed in version 3.8:Symbolic links and junctions are now resolved on Windows.
Changed in version 3.10:Thestrict parameter was added.
Changed in version 3.14:The
ALLOW_MISSINGvalue for thestrict parameterwas added.
- os.path.ALLOW_MISSING¶
Special value used for thestrict argument in
realpath().Added in version 3.14.
- os.path.relpath(path,start=os.curdir)¶
Return a relative filepath topath either from the current directory orfrom an optionalstart directory. This is a path computation: thefilesystem is not accessed to confirm the existence or nature ofpath orstart. On Windows,
ValueErroris raised whenpath andstartare on different drives.start defaults to
os.curdir.Changed in version 3.6:Accepts apath-like object.
- os.path.samefile(path1,path2,/)¶
Return
Trueif both pathname arguments refer to the same file or directory.This is determined by the device number and i-node number and raises anexception if anos.stat()call on either pathname fails.Changed in version 3.2:Added Windows support.
Changed in version 3.4:Windows now uses the same implementation as all other platforms.
Changed in version 3.6:Accepts apath-like object.
- os.path.sameopenfile(fp1,fp2)¶
Return
Trueif the file descriptorsfp1 andfp2 refer to the same file.Changed in version 3.2:Added Windows support.
Changed in version 3.6:Accepts apath-like object.
- os.path.samestat(stat1,stat2,/)¶
Return
Trueif the stat tuplesstat1 andstat2 refer to the same file.These structures may have been returned byos.fstat(),os.lstat(), oros.stat(). This function implements theunderlying comparison used bysamefile()andsameopenfile().Changed in version 3.4:Added Windows support.
- os.path.split(path,/)¶
Split the pathnamepath into a pair,
(head,tail)wheretail is thelast pathname component andhead is everything leading up to that. Thetail part will never contain a slash; ifpath ends in a slash,tailwill be empty. If there is no slash inpath,head will be empty. Ifpath is empty, bothhead andtail are empty. Trailing slashes arestripped fromhead unless it is the root (one or more slashes only). Inall cases,join(head,tail)returns a path to the same location aspath(but the strings may differ). Also see the functionsdirname()andbasename().Changed in version 3.6:Accepts apath-like object.
- os.path.splitdrive(path,/)¶
Split the pathnamepath into a pair
(drive,tail)wheredrive is eithera mount point or the empty string. On systems which do not use drivespecifications,drive will always be the empty string. In all cases,drive+tailwill be the same aspath.On Windows, splits a pathname into drive/UNC sharepoint and relative path.
If the path contains a drive letter, drive will contain everythingup to and including the colon:
>>>splitdrive("c:/dir")("c:", "/dir")
If the path contains a UNC path, drive will contain the host nameand share:
>>>splitdrive("//host/computer/dir")("//host/computer", "/dir")
Changed in version 3.6:Accepts apath-like object.
- os.path.splitroot(path,/)¶
Split the pathnamepath into a 3-item tuple
(drive,root,tail)wheredrive is a device name or mount point,root is a string of separatorsafter the drive, andtail is everything after the root. Any of theseitems may be the empty string. In all cases,drive+root+tailwillbe the same aspath.On POSIX systems,drive is always empty. Theroot may be empty (ifpath isrelative), a single forward slash (ifpath is absolute), or two forward slashes(implementation-defined perIEEE Std 1003.1-2017; 4.13 Pathname Resolution.)For example:
>>>splitroot('/home/sam')('', '/', 'home/sam')>>>splitroot('//home/sam')('', '//', 'home/sam')>>>splitroot('///home/sam')('', '/', '//home/sam')
On Windows,drive may be empty, a drive-letter name, a UNC share, or a devicename. Theroot may be empty, a forward slash, or a backward slash. Forexample:
>>>splitroot('C:/Users/Sam')('C:', '/', 'Users/Sam')>>>splitroot('//Server/Share/Users/Sam')('//Server/Share', '/', 'Users/Sam')
Added in version 3.12.
- os.path.splitext(path,/)¶
Split the pathnamepath into a pair
(root,ext)such thatroot+ext==path, and the extension,ext, is empty or begins with a period and contains atmost one period.If the path contains no extension,ext will be
'':>>>splitext('bar')('bar', '')
If the path contains an extension, thenext will be set to this extension,including the leading period. Note that previous periods will be ignored:
>>>splitext('foo.bar.exe')('foo.bar', '.exe')>>>splitext('/foo/bar.exe')('/foo/bar', '.exe')
Leading periods of the last component of the path are considered tobe part of the root:
>>>splitext('.cshrc')('.cshrc', '')>>>splitext('/foo/....jpg')('/foo/....jpg', '')
Changed in version 3.6:Accepts apath-like object.
- os.path.supports_unicode_filenames¶
Trueif arbitrary Unicode strings can be used as file names (within limitationsimposed by the file system).