10.1.os.path — Common pathname manipulations

This module implements some useful functions on pathnames. To read orwrite files seeopen(), and for accessing the filesystem see theos module.

Note

On Windows, many of these functions do not properly support UNC pathnames.splitunc() andismount() do handle them correctly.

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

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

  • macpath for old-style MacOS paths

  • os2emxpath for OS/2 EMX paths

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

New in version 1.5.2.

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

os.path.commonprefix(list)

Return the longest path prefix (taken character-by-character) that is a prefixof all paths inlist. Iflist is empty, return the empty string ('').Note that this may return invalid paths because it works a character at a time.

os.path.dirname(path)

Return the directory name of pathnamepath. This is the first element ofthe pair returned by passingpath to the functionsplit().

os.path.exists(path)

ReturnTrue ifpath refers to an existing path. ReturnsFalse forbroken symbolic links. On some platforms, this function may returnFalse ifpermission is not granted to executeos.stat() on the requested file, evenif thepath physically exists.

os.path.lexists(path)

ReturnTrue ifpath refers to an existing path. ReturnsTrue forbroken symbolic links. Equivalent toexists() on platforms lackingos.lstat().

New in version 2.4.

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,HOME andUSERPROFILE will be used if set,otherwise a combination ofHOMEPATH andHOMEDRIVE will beused. An initial~user is handled by stripping the last directory componentfrom the created user path derived above.

If the expansion fails or if the path does not begin with a tilde, the path isreturned unchanged.

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}.

os.path.getatime(path)

Return the time of last access ofpath. The return value is a number givingthe number of seconds since the epoch (see thetime module). Raiseos.error if the file does not exist or is inaccessible.

New in version 1.5.2.

Changed in version 2.3:Ifos.stat_float_times() returnsTrue, the result is a floating pointnumber.

os.path.getmtime(path)

Return the time of last modification ofpath. The return value is a numbergiving the number of seconds since the epoch (see thetime module).Raiseos.error if the file does not exist or is inaccessible.

New in version 1.5.2.

Changed in version 2.3:Ifos.stat_float_times() returnsTrue, the result is a floating pointnumber.

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). Raiseos.error if the file does not exist oris inaccessible.

New in version 2.3.

os.path.getsize(path)

Return the size, in bytes, ofpath. Raiseos.error if the file doesnot exist or is inaccessible.

New in version 1.5.2.

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.

os.path.isfile(path)

ReturnTrue ifpath is an existing regular file. This follows symboliclinks, so bothislink() andisfile() can be true for the same path.

os.path.isdir(path)

ReturnTrue ifpath is an existing directory. This follows symboliclinks, so bothislink() andisdir() can be true for the same path.

os.path.islink(path)

ReturnTrue ifpath refers to a directory entry that is a symbolic link.AlwaysFalse if symbolic links are not supported by the Python runtime.

os.path.ismount(path)

ReturnTrue if pathnamepath is amount point: a point in a filesystem where a different file system has been mounted. The function checkswhetherpath’s parent,path/.., is on a different device thanpath,or whetherpath/.. andpath point to the same i-node on the samedevice — this should detect mount points for all Unix and POSIX variants.

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 (os.sep) following each non-empty part except thelast, meaning that the result will only end in a separator if the lastpart is empty. If a component is an absolute path, all previouscomponents are thrown away and joining continues from the absolute pathcomponent.

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.

os.path.normcase(path)

Normalize the case of a pathname. On Unix and Mac OS X, this returns thepath unchanged; on case-insensitive filesystems, it converts the path tolowercase. On Windows, it also converts forward slashes to backward slashes.

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

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 operating system).

New in version 2.2.

os.path.relpath(path[,start])

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.

start defaults toos.curdir.

Availability: Windows, Unix.

New in version 2.6.

os.path.samefile(path1,path2)

ReturnTrue if both pathname arguments refer to the same file or directory(as indicated by device number and i-node number). Raise an exception if anos.stat() call on either pathname fails.

Availability: Unix.

os.path.sameopenfile(fp1,fp2)

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

Availability: Unix.

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.

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

os.path.splitdrive(path)

Split the pathnamepath into a pair(drive,tail) wheredrive is eithera drive specification 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.

New in version 1.3.

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 2.6:Earlier versions could produce an empty root when the only period was thefirst character.

os.path.splitunc(path)

Split the pathnamepath into a pair(unc,rest) so thatunc is the UNCmount point (such asr'\\host\mount'), if present, andrest the rest ofthe path (such asr'\path\file.ext'). For paths containing drive letters,unc will always be the empty string.

Availability: Windows.

os.path.walk(path,visit,arg)

Calls the functionvisit with arguments(arg,dirname,names) for eachdirectory in the directory tree rooted atpath (includingpath itself, if itis a directory). The argumentdirname specifies the visited directory, theargumentnames lists the files in the directory (gotten fromos.listdir(dirname)). Thevisit function may modifynames to influencethe set of directories visited belowdirname, e.g. to avoid visiting certainparts of the tree. (The object referred to bynames must be modified inplace, usingdel or slice assignment.)

Note

Symbolic links to directories are not treated as subdirectories, and thatwalk() therefore will not visit them. To visit linked directories you mustidentify them withos.path.islink(file) andos.path.isdir(file), andinvokewalk() as necessary.

Note

This function is deprecated and has been removed in Python 3 in favor ofos.walk().

os.path.supports_unicode_filenames

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

New in version 2.3.