This module contains a number of functions that deal with long filenames in a platform independent way. In other words, without having to deal with forward and backward slashes, colons, and whatnot.
Example: Using the os.path module to handle filename
# File: `os-path-example-1.py <os-path-example-1.py>`__
import os
filename = "my/little/pony"
print "using", os.name, "..."
print "split", "=>", os.path.split(filename)
print "splitext", "=>", os.path.splitext(filename)
print "dirname", "=>", os.path.dirname(filename)
print "basename", "=>", os.path.basename(filename)
print "join", "=>", os.path.join(os.path.dirname(filename),
os.path.basename(filename))
using nt ...
split => ('my/little', 'pony')
splitext => ('my/little/pony', '')
dirname => my/little
basename => pony
join => my/little\pony
Note that split only splits off a single item.
This module also contains a number of functions that allow you to quickly figure out what a filename represents:
Example: Using the os.path module to check what a filename represents
# File: `os-path-example-2.py <os-path-example-2.py>`__
import os
FILES = (
os.curdir,
"/",
"file",
"/file",
"samples",
"samples/sample.jpg",
"directory/file",
"../directory/file",
"/directory/file"
)
for file in FILES:
print file, "=>",
if os.path.exists(file):
print "EXISTS",
if os.path.isabs(file):
print "ISABS",
if os.path.isdir(file):
print "ISDIR",
if os.path.isfile(file):
print "ISFILE",
if os.path.islink(file):
print "ISLINK",
if os.path.ismount(file):
print "ISMOUNT",
print
. => EXISTS ISDIR / => EXISTS ISABS ISDIR ISMOUNT file => /file => ISABS samples => EXISTS ISDIR samples/sample.jpg => EXISTS ISFILE directory/file => ../directory/file => /directory/file => ISABS
The expanduser function treats a user name shortcut in the same way as most modern Unix shells (it doesn’t work well on Windows).
Example: Using the os.path module to insert the user name into a filename
# File: `os-path-expanduser-example-1.py <os-path-expanduser-example-1.py>`__
import os
print os.path.expanduser("~/.pythonrc")
/home/effbot/.pythonrc
The expandvars function inserts environment variables into a filename:
Example: Using the os.path module to insert variables into a filename
# File: `os-path-expandvars-example-1.py <os-path-expandvars-example-1.py>`__
import os
os.environ["USER"] = "user"
print os.path.expandvars("/home/$USER/config")
print os.path.expandvars("$USER/folders")
/home/user/config user/folders