The os.path Module
The os.path module contains functions that deal with long filenames (pathnames) in various ways. To use this module, import the os module, and access this module
as os.path.
Working with Filenames
The os.path module contains a number of functions that deal with long
filenames in a platform independent way. In other words, you won’t have to deal with forward and backward slashes, colons, and whatnot. Let’s look at Example 1-42.
Example 1-42. Using the os.path Module to Handle Filename
File: 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\ponyNote that split only splits off a single item.
The os.path module also contains a number of functions that allow you to
quickly figure out what a filename represents, as shown in Example 1-43.
Example 1-43. Using the os.path Module to Check What a Filename Represents
File: 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, "=>", ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access