(False, False)
>>> os.path.exists(r'c:\Users\Brian')
False
>>> os.path.exists(r'c:\Users\Default')
True
>>> os.path.getsize(r'C:\autoexec.bat')
24
The os.path.isdir and os.path.isfile calls tell us whether a filename is a directory or
a simple file; both return False if the named file does not exist (that is, nonexistence
implies negation). We also get calls for splitting and joining directory path strings,
which automatically use the directory name conventions on the platform on which
Python is running:
>>> os.path.split(r'C:\temp\data.txt')
('C:\\temp', 'data.txt')
>>> os.path.join(r'C:\temp', 'output.txt')
'C:\\temp\\output.txt'
>>> name = r'C:\temp\data.txt' # Windows paths
>>> os.path.dirname(name), os.path.basename(name)
('C:\\temp', 'data.txt')
>>> name = '/home/lutz/temp/data.txt' # Unix-style paths
>>> os.path.dirname(name), os.path.basename(name)
('/home/lutz/temp', 'data.txt')
>>> os.path.splitext(r'C:\PP4thEd\Examples\PP4E\PyDemos.pyw')
('C:\\PP4thEd\\Examples\\PP4E\\PyDemos', '.pyw')
os.path.split separates a filename from its directory path, and os.path.join puts them
back together—all in entirely portable fashion using the path conventions of the ma-
chine on which they are called. The dirname and basename calls here return the first and
second items returned by a split simply as a convenience, and splitext strips the file
extension (after the last .). Subtle point: it’s almost equivalent to use string split and
join method calls with the portable os.sep string, but not exactly:
>>> os.sep
'\\'
>>> pathname = r'C:\PP4thEd\Examples\PP4E\PyDemos.pyw'
>>> os.path.split(pathname) # split file from dir
('C:\\PP4thEd\\Examples\\PP4E', 'PyDemos.pyw')
>>> pathname.split(os.sep) # split on every slash
['C:', 'PP4thEd', 'Examples', 'PP4E', 'PyDemos.pyw']
>>> os.sep.join(pathname.split(os.sep))
'C:\\PP4thEd\\Examples\\PP4E\\PyDemos.pyw'
>>> os.path.join(*pathname.split(os.sep))
'C:PP4thEd\\Examples\\PP4E\\PyDemos.pyw'
Introducing the os Module | 93