📝 Edit on GitHub
OS library
Get current path
Working directory
Absolute path to directory where you are executing from.
os.getcwd()
This seems like a longer equivalent:
os.path.realpath(os.curdir)
Where os.durdir
is '.'
.
Path to script
Path of the current file.
__file__
NB. __file__
is not defined in the interactive console.
Absolute path to the current file. Note the realpath is safer than abspath.
os.path.realpath(__file__)
Check access to path
exists
os.path.exists(path)
check
# Exists
os.check(path, os.F_OK)
# Read
os.check(path, os.R_OK)
# Write
os.check(path, os.W_OK)
# Execte
os.check(path, os.X_OK)
Check type
os.path.isdir(path)
os.path.isfile(path)
os.path.islink(path)
os.path.isabs(path)
Format path
Absolute
os.path.abspath(path)
Real
The “canonical” path.
os.path.realpath(path)
- Resolves symlinks.
- Does not resolve
~
.
Relative
Convert to relative.
os.path.relpath(path
Expand user path
os.path.expanduser("~/file.txt")
Join
os.path.join(foo, bar)
Split
Get directory
Of a file.
os.path.dirname('foo/bar/baz.txt')
# => 'foo/bar'
Of a directory.
os.path.dirname('foo/bar')
# => 'foo'
Note if it ends in forwardslash it will just remove that.
os.path.dirname('foo/bar/')
# => 'foo/bar'
Base
Get the last part of a path - whether a directory or filename.
os.path.basename('foo/bar/baz.txt')
# => 'baz.txt'
os.path.basename('foo/bar')
# => 'bar'
If ending in forwardslash is empty.
os.path.basename('foo/bar/')
# => ''
Traverse
Parent directory
os.path.pardir
# => '..'
os.path.dirname(path)