[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

The last join call require individual arguments (hence the *) but doesn’t insert a first
slash because of the Windows drive syntax; use the preceding str.join method instead
if the difference matters. The normpath call comes in handy if your paths become a
jumble of Unix and Windows separators:


>>> mixed
'C:\\temp\\public/files/index.html'
>>> os.path.normpath(mixed)
'C:\\temp\\public\\files\\index.html'
>>> print(os.path.normpath(r'C:\temp\\sub\.\file.ext'))
C:\temp\sub\file.ext

This module also has an abspath call that portably returns the full directory pathname
of a file; it accounts for adding the current directory as a path prefix, .. parent syntax,
and more:


>>> os.chdir(r'C:\Users')
>>> os.getcwd()
'C:\\Users'
>>> os.path.abspath('') # empty string means the cwd
'C:\\Users'

>>> os.path.abspath('temp') # expand to full pathname in cwd
'C:\\Users\\temp'
>>> os.path.abspath(r'PP4E\dev') # partial paths relative to cwd
'C:\\Users\\PP4E\\dev'

>>> os.path.abspath('.') # relative path syntax expanded
'C:\\Users'
>>> os.path.abspath('..')
'C:\\'
>>> os.path.abspath(r'..\examples')
'C:\\examples'

>>> os.path.abspath(r'C:\PP4thEd\chapters') # absolute paths unchanged
'C:\\PP4thEd\\chapters'
>>> os.path.abspath(r'C:\temp\spam.txt')
'C:\\temp\\spam.txt'

Because filenames are relative to the current working directory when they aren’t fully
specified paths, the os.path.abspath function helps if you want to show users what
directory is truly being used to store a file. On Windows, for example, when GUI-based
programs are launched by clicking on file explorer icons and desktop shortcuts, the
execution directory of the program is the clicked file’s home directory, but that is not
always obvious to the person doing the clicking; printing a file’s abspath can help.


Running Shell Commands from Scripts


The os module is also the place where we run shell commands from within Python
scripts. This concept is intertwined with others, such as streams, which we won’t cover
fully until the next chapter, but since this is a key concept employed throughout this


94 | Chapter 2: System Tools

Free download pdf