os.path — Common pathname manipulations

Source code:Lib/posixpath.py (for POSIX) andLib/ntpath.py (for Windows NT).


This module implements some useful functions on pathnames. To read orwrite files seeopen(), and for accessing the filesystem see theos module. The path parameters can be passed as either strings,or bytes. Applications are encouraged to represent file names as(Unicode) character strings. Unfortunately, some file names may not berepresentable as strings on Unix, so applications that need to supportarbitrary file names on Unix should use bytes objects to representpath names. Vice versa, using bytes objects cannot represent all filenames on Windows (in the standardmbcs encoding), hence Windowsapplications should use string objects to access all files.

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:

  • posixpath for UNIX-style paths

  • ntpath for 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 functionnormpath() 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 functionsplit(). 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 sequencepaths. RaiseValueError ifpaths contain both absoluteand relative pathnames, thepaths are on the different drives orifpaths is empty. Unlikecommonprefix(), this returns avalid path.

Availability: Unix, Windows.

New in version 3.5.

Changed in version 3.6:Accepts a sequence ofpath-like objects.

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, seecommonpath().

>>>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 functionsplit().

Changed in version 3.6:Accepts apath-like object.

os.path.exists(path)

ReturnTrue ifpath refers to an existing path or an openfile descriptor. ReturnsFalse for broken symbolic links. Onsome platforms, this function may returnFalse if 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:True is returned if it is an open file descriptor,False otherwise.

Changed in version 3.6:Accepts apath-like object.

os.path.lexists(path)

ReturnTrue ifpath refers to an existing path. ReturnsTrue forbroken 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~user replaced 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,USERPROFILE will be used if set, otherwise a combinationofHOMEPATH andHOMEDRIVE will be used. An initial~user is handled by stripping the last directory component from the createduser path derived above.

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 usesHOME on Windows.

os.path.expandvars(path)

Return the argument with environment variables expanded. Substrings of the form$name or${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$name and${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 thetime module). RaiseOSError if 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 thetime module).RaiseOSError if 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 (seethetime module). RaiseOSError if 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. RaiseOSError if the file doesnot exist or is inaccessible.

Changed in version 3.6:Accepts apath-like object.

os.path.isabs(path)

ReturnTrue ifpath is an absolute pathname. On Unix, that means itbegins with a slash, on Windows that it begins with a (back)slash after choppingoff a potential drive letter.

Changed in version 3.6:Accepts apath-like object.

os.path.isfile(path)

ReturnTrue ifpath is anexisting regular 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)

ReturnTrue ifpath is anexisting directory. Thisfollows symbolic links, so bothislink() andisdir() can be truefor the same path.

Changed in version 3.6:Accepts apath-like object.

os.path.islink(path)

ReturnTrue ifpath refers to anexisting directoryentry that is a symbolic link. AlwaysFalse if symbolic links are notsupported by the Python runtime.

Changed in version 3.6:Accepts apath-like object.

os.path.ismount(path)

ReturnTrue if 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 Windows, a drive letter root and a share UNC arealways mount points, and for any other pathGetVolumePathName is calledto see if it is different from the input path.

New in version 3.4:Support for detecting non-root mount points on Windows.

Changed in version 3.6:Accepts apath-like object.

os.path.join(path,*paths)

Join one or more path components intelligently. The return value is theconcatenation ofpath and any members of*paths with exactly onedirectory separator following each non-empty part except the last, meaningthat the result will only end in a separator if the last part is empty. Ifa component is an absolute path, all previous components are thrown awayand joining continues from the absolute path component.

On Windows, the drive letter is not reset when an absolute path component(e.g.,r'\foo') is encountered. If a component contains a driveletter, all previous components are thrown away and the drive letter isreset. Note that 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 thatA//B,A/B/,A/./B andA/foo/../B allbecomeA/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().

Changed in version 3.6:Accepts apath-like object.

os.path.realpath(path)

Return the canonical path of the specified filename, eliminating any symboliclinks encountered in the path (if they are supported by the operatingsystem).

Note

When symbolic link cycles occur, the returned path will be one member ofthe cycle, but no guarantee is made about which member that will be.

Changed in version 3.6:Accepts apath-like object.

Changed in version 3.8:Symbolic links and junctions are now resolved on Windows.

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,ValueError is raised whenpath andstartare on different drives.

start defaults toos.curdir.

Availability: Unix, Windows.

Changed in version 3.6:Accepts apath-like object.

os.path.samefile(path1,path2)

ReturnTrue if 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.

Availability: Unix, Windows.

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)

ReturnTrue if the file descriptorsfp1 andfp2 refer to the same file.

Availability: Unix, Windows.

Changed in version 3.2:Added Windows support.

Changed in version 3.6:Accepts apath-like object.

os.path.samestat(stat1,stat2)

ReturnTrue if 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().

Availability: Unix, Windows.

Changed in version 3.4:Added Windows support.

Changed in version 3.6:Accepts apath-like object.

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+tail will 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.e.g.splitdrive("c:/dir") returns("c:","/dir")

If the path contains a UNC path, drive will contain the host nameand share, up to but not including the fourth separator.e.g.splitdrive("//host/computer/dir") returns("//host/computer","/dir")

Changed in version 3.6:Accepts apath-like object.

os.path.splitext(path)

Split the pathnamepath into a pair(root,ext) such thatroot+ext==path, andext is empty or begins with a period and contains at most oneperiod. Leading periods on the basename are ignored;splitext('.cshrc')returns('.cshrc','').

Changed in version 3.6:Accepts apath-like object.

os.path.supports_unicode_filenames

True if arbitrary Unicode strings can be used as file names (within limitationsimposed by the file system).