4. When I called the
function, I used a Linux-style pathname (forward slashes, no drive letter) even
though I’m on Windows. This is one of the places where Python tries to paper over the differences between
While we’re on the subject of directories, I want to point out the
functions for manipulating filenames and directory names.
>>> import os
>>> print(os.path.join('/Users/pilgrim/diveintopython3/examples/', 'humansize.py'))
>>> print(os.path.join('/Users/pilgrim/diveintopython3/examples', 'humansize.py'))
>>> print(os.path.join(os.path.expanduser('~'), 'diveintopython3', 'examples', 'humansize.py'))
function constructs a pathname out of one or more partial pathnames. In this case, it
simply concatenates strings.
2. In this slightly less trivial case,
will add an extra slash to the pathname before joining it to the filename.
It’s a backslash instead of a forward slash, because I constructed this example on Windows. If you replicate
this example on Linux or Mac OS X, you’ll see a forward slash instead. Python can access the file regardless
of what kind of slashes you use in the pathname.
function will expand a pathname that uses
to represent the current user’s
home directory. This works on any platform where users have a home directory, including Linux, Mac OS X,
and Windows. The returned path does not have a trailing slash, but the
4. Combining these techniques, you can easily construct pathnames for directories and files in the user’s home
function can take any number of arguments. I was overjoyed when I
discovered this, since
is one of the stupid little functions I always need to write when
building up my toolbox in a new language. Do not write this stupid little function in Python; smart people
have already taken care of it for you.