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 see open()
, 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 standard mbcs
encoding), hence Windowsapplications should use string objects to access all files.
Unlike a unix shell, Python does not do any automatic path expansions.Functions such as expanduser()
and expandvars()
can be invokedexplicitly when an application desires shell-like path expansion. (See alsothe glob
module.)
See also
On Mac OS X, it's in the Python framework in /System/Library/Frameworks/Python.framework/Resources. Full path is: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python. (The format for PYTHONPATH is OS-dependent but should mimic the PATH environment variable.) An installation-dependent list of directories configured at the time Python is installed; The resulting search path is accessible in the Python variable sys.path, which is obtained from a module named sys:. Recent Python.org versions of Python for macOS no longer respect the DYLDLIBRARYPATH environment variable for extending the dynamic library search path, and the envvar is completely invisible to the Python process. This is the case since at least Python 3.7.7 and Python 3.8.2.
The pathlib
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 is always in one of the different formats. They all have thesame interface:
posixpath
for UNIX-style pathsntpath
for Windows paths
Changed in version 3.8: exists()
, lexists()
, isdir()
, isfile()
,islink()
, and ismount()
now return False
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 pathname path. On mostplatforms, this is equivalent to calling the function normpath()
asfollows: normpath(join(os.getcwd(),path))
.
Changed in version 3.6: Accepts a path-like object.
os.path.
basename
(path)¶Return the base name of pathname path. This is the second element of thepair returned by passing path to the function split()
. Note thatthe result of this function is differentfrom the Unix basename program; where basename for'/foo/bar/'
returns 'bar'
, the basename()
function returns anempty string ('
).
Changed in version 3.6: Accepts a path-like object.
os.path.
commonpath
(paths)¶Return the longest common sub-path of each pathname in the sequencepaths. Raise ValueError
if paths contain both absoluteand relative pathnames, the paths are on the different drives orif paths is empty. Unlike commonprefix()
, this returns avalid path.
Availability: Unix, Windows.
Changed in version 3.6: Accepts a sequence of path-like objects.
os.path.
commonprefix
(list)¶Return the longest path prefix (taken character-by-character) that is aprefix of all paths in list. If list 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()
.
Changed in version 3.6: Accepts a path-like object.
os.path.
dirname
(path)¶Return the directory name of pathname path. This is the first element ofthe pair returned by passing path to the function split()
.
Changed in version 3.6: Accepts a path-like object.
os.path.
exists
(path)¶Return True
if path refers to an existing path or an openfile descriptor. Returns False
for broken symbolic links. Onsome platforms, this function may return False
if permission isnot granted to execute os.stat()
on the requested file, evenif the path 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 a path-like object.
os.path.
lexists
(path)¶Return True
if path refers to an existing path. Returns True
forbroken symbolic links. Equivalent to exists()
on platforms lackingos.lstat()
.
Changed in version 3.6: Accepts a path-like object.
os.path.
expanduser
(path)¶On Unix and Windows, return the argument with an initial component of ~
or~user
replaced by that user’s home directory.
On Unix, an initial ~
is replaced by the environment variable HOME
if it is set; otherwise the current user’s home directory is looked up in thepassword directory through the built-in module pwd
. An initial ~user
is looked up directly in the password directory.
On Windows, USERPROFILE
will be used if set, otherwise a combinationof HOMEPATH
and HOMEDRIVE
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 a path-like object.
Changed in version 3.8: No longer uses HOME
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 a path-like object.
os.path.
getatime
(path)¶Return the time of last access of path. The return value is a floating point number givingthe number of seconds since the epoch (see the time
module). RaiseOSError
if the file does not exist or is inaccessible.
os.path.
getmtime
(path)¶Return the time of last modification of path. The return value is a floating point numbergiving the number of seconds since the epoch (see the time
module).Raise OSError
if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-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 for path.The return value is a number giving the number of seconds since the epoch (seethe time
module). Raise OSError
if the file does not exist oris inaccessible.
Changed in version 3.6: Accepts a path-like object.
os.path.
getsize
(path)¶Return the size, in bytes, of path. Raise OSError
if the file doesnot exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object.
os.path.
isabs
(path)¶Return True
if path 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 a path-like object.
os.path.
isfile
(path)¶Return True
if path is an existing
regular file.This follows symbolic links, so both islink()
and isfile()
canbe true for the same path.
Changed in version 3.6: Accepts a path-like object.
os.path.
isdir
(path)¶Return True
if path is an existing
directory. Thisfollows symbolic links, so both islink()
and isdir()
can be truefor the same path.
Changed in version 3.6: Accepts a path-like object.
os.path.
islink
(path)¶Return True
if path refers to an existing
directoryentry that is a symbolic link. Always False
if symbolic links are notsupported by the Python runtime.
Changed in version 3.6: Accepts a path-like object.
os.path.
ismount
(path)¶Return True
if pathname path is a mount point: a point in afile system where a different file system has been mounted. On POSIX, thefunction checks whether path’s parent, path/..
, is on a differentdevice than path, or whether path/..
and path 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 path GetVolumePathName
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 a path-like object.
os.path.
join
(path, *paths)¶Join one or more path components intelligently. The return value is theconcatenation of path 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 drive C:
(c:foo
), not c:foo
.
Changed in version 3.6: Accepts a path-like object for path and paths.
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 a path-like object.
os.path.
normpath
(path)¶Normalize a pathname by collapsing redundant separators and up-levelreferences so that A//B
, A/B/
, A/./B
and A/foo/../B
allbecome A/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, use normcase()
.
Changed in version 3.6: Accepts a path-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 a path-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 to path either from the current directory orfrom an optional start directory. This is a path computation: thefilesystem is not accessed to confirm the existence or nature of path orstart.
start defaults to os.curdir
.
Availability: Unix, Windows.
Changed in version 3.6: Accepts a path-like object.
os.path.
samefile
(path1, path2)¶Return True
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 an os.stat()
call on either pathname fails.
Python Library Path Mac
Availability: Unix, Windows.
Changed in version 3.4: Windows now uses the same implementation as all other platforms.
Changed in version 3.6: Accepts a path-like object.
os.path.
sameopenfile
(fp1, fp2)¶Return True
if the file descriptors fp1 and fp2 refer to the same file.
Availability: Unix, Windows.
Changed in version 3.6: Accepts a path-like object.
os.path.
samestat
(stat1, stat2)¶Return True
if the stat tuples stat1 and stat2 refer to the same file.These structures may have been returned by os.fstat()
,os.lstat()
, or os.stat()
. This function implements theunderlying comparison used by samefile()
and sameopenfile()
.
Availability: Unix, Windows.
Changed in version 3.6: Accepts a path-like object.
os.path.
split
(path)¶Split the pathname path into a pair, (head,tail)
where tail is thelast pathname component and head is everything leading up to that. Thetail part will never contain a slash; if path ends in a slash, tailwill be empty. If there is no slash in path, head will be empty. Ifpath is empty, both head and tail are empty. Trailing slashes arestripped from head unless it is the root (one or more slashes only). Inall cases, join(head,tail)
returns a path to the same location as path(but the strings may differ). Also see the functions dirname()
andbasename()
.
Changed in version 3.6: Accepts a path-like object.
os.path.
splitdrive
(path)¶Split the pathname path into a pair (drive,tail)
where drive 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 as path.
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 a path-like object.
os.path.
splitext
(path)¶Split the pathname path into a pair (root,ext)
such that root+extpath
, and ext is empty or begins with a period and contains at most oneperiod. Leading periods on the basename are ignored; splitext('.cshrc')
returns ('.cshrc',')
.
Macos Python Library Path
Changed in version 3.6: Accepts a path-like object.
os.path.
supports_unicode_filenames
¶True
if arbitrary Unicode strings can be used as file names (within limitationsimposed by the file system).
Bob Savage <bobsavage@mac.com>
Python on a Macintosh running Mac OS X is in principle very similar to Python onany other Unix platform, but there are a number of additional features such asthe IDE and the Package Manager that are worth pointing out.
4.1. Getting and Installing MacPython¶
Mac OS X 10.8 comes with Python 2.7 pre-installed by Apple. If you wish, youare invited to install the most recent version of Python 3 from the Pythonwebsite (https://www.python.org). A current “universal binary” build of Python,which runs natively on the Mac’s new Intel and legacy PPC CPU’s, is availablethere.
What you get after installing is a number of things:
A
Python3.8
folder in yourApplications
folder. In hereyou find IDLE, the development environment that is a standard part of officialPython distributions; PythonLauncher, which handles double-clicking Pythonscripts from the Finder; and the “Build Applet” tool, which allows you topackage Python scripts as standalone applications on your system.A framework
/Library/Frameworks/Python.framework
, which includes thePython executable and libraries. The installer adds this location to your shellpath. To uninstall MacPython, you can simply remove these three things. Asymlink to the Python executable is placed in /usr/local/bin/.
The Apple-provided build of Python is installed in/System/Library/Frameworks/Python.framework
and /usr/bin/python
,respectively. You should never modify or delete these, as they areApple-controlled and are used by Apple- or third-party software. Remember thatif you choose to install a newer Python version from python.org, you will havetwo different but functional Python installations on your computer, so it willbe important that your paths and usages are consistent with what you want to do.
IDLE includes a help menu that allows you to access Python documentation. If youare completely new to Python you should start reading the tutorial introductionin that document.
If you are familiar with Python on other Unix platforms you should read thesection on running Python scripts from the Unix shell.
4.1.1. How to run a Python script¶
Your best way to get started with Python on Mac OS X is through the IDLEintegrated development environment, see section The IDE and use the Help menuwhen the IDE is running.
If you want to run Python scripts from the Terminal window command line or fromthe Finder you first need an editor to create your script. Mac OS X comes with anumber of standard Unix command line editors, vim andemacs among them. If you want a more Mac-like editor,BBEdit or TextWrangler from Bare Bones Software (seehttp://www.barebones.com/products/bbedit/index.html) are good choices, as isTextMate (see https://macromates.com/). Other editors includeGvim (http://macvim-dev.github.io/macvim/) and Aquamacs(http://aquamacs.org/).
To run your script from the Terminal window you must make sure that/usr/local/bin
is in your shell search path.
To run your script from the Finder you have two options:
Drag it to PythonLauncher
Select PythonLauncher as the default application to open yourscript (or any .py script) through the finder Info window and double-click it.PythonLauncher has various preferences to control how your script islaunched. Option-dragging allows you to change these for one invocation, or useits Preferences menu to change things globally.
4.1.2. Running scripts with a GUI¶
With older versions of Python, there is one Mac OS X quirk that you need to beaware of: programs that talk to the Aqua window manager (in other words,anything that has a GUI) need to be run in a special way. Use pythonwinstead of python to start such scripts.
With Python 3.8, you can use either python or pythonw.
4.1.3. Configuration¶
Python on OS X honors all standard Unix environment variables such asPYTHONPATH
, but setting these variables for programs started from theFinder is non-standard as the Finder does not read your .profile
or.cshrc
at startup. You need to create a file~/.MacOSX/environment.plist
. See Apple’s Technical Document QA1067 fordetails.
For more information on installation Python packages in MacPython, see sectionInstalling Additional Python Packages.
4.2. The IDE¶
Pythonpath
MacPython ships with the standard IDLE development environment. A goodintroduction to using IDLE can be found athttp://www.hashcollision.org/hkn/python/idle_intro/index.html.
4.3. Installing Additional Python Packages¶
There are several methods to install additional Python packages:
Packages can be installed via the standard Python distutils mode (
pythonsetup.pyinstall
).Many packages can also be installed via the setuptools extensionor pip wrapper, see https://pip.pypa.io/.
4.4. GUI Programming on the Mac¶
There are several options for building GUI applications on the Mac with Python.
PyObjC is a Python binding to Apple’s Objective-C/Cocoa framework, which isthe foundation of most modern Mac development. Information on PyObjC isavailable from https://pypi.org/project/pyobjc/.
The standard Python GUI toolkit is tkinter
, based on the cross-platformTk toolkit (https://www.tcl.tk). An Aqua-native version of Tk is bundled with OSX by Apple, and the latest version can be downloaded and installed fromhttps://www.activestate.com; it can also be built from source.
wxPython is another popular cross-platform GUI toolkit that runs natively onMac OS X. Packages and documentation are available from https://www.wxpython.org.
PyQt is another popular cross-platform GUI toolkit that runs natively on MacOS X. More information can be found athttps://riverbankcomputing.com/software/pyqt/intro.
4.5. Distributing Python Applications on the Mac¶
The “Build Applet” tool that is placed in the MacPython 3.6 folder is fine forpackaging small Python scripts on your own machine to run as a standard Macapplication. This tool, however, is not robust enough to distribute Pythonapplications to other users.
The standard tool for deploying standalone Python applications on the Mac ispy2app. More information on installing and using py2app can be foundat http://undefined.org/python/#py2app.
4.6. Other Resources¶
The MacPython mailing list is an excellent support resource for Python users anddevelopers on the Mac:
Mac Upgrade Python 3
Another useful resource is the MacPython wiki: