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

(yzsuai) #1

The input filename argument here is given without an explicit directory path (though
you could add one to page files in another directory). If you need to run in a different
working directory, call the os.chdir function to change to a new directory; your code
will run relative to the new directory for the rest of the program (or until the next
os.chdir call). The next chapter will have more to say about the notion of a current
working directory, and its relation to module imports when it explores script execution
context.


Portability Constants


The os module also exports a set of names designed to make cross-platform program-
ming simpler. The set includes platform-specific settings for path and directory sepa-
rator characters, parent and current directory indicators, and the characters used to
terminate lines on the underlying computer.


>>> os.pathsep, os.sep, os.pardir, os.curdir, os.linesep
(';', '\\', '..', '.', '\r\n')

os.sep is whatever character is used to separate directory components on the platform
on which Python is running; it is automatically preset to \ on Windows, / for POSIX
machines, and : on some Macs. Similarly, os.pathsep provides the character that sep-
arates directories on directory lists, : for POSIX and ; for DOS and Windows.


By using such attributes when composing and decomposing system-related strings in
our scripts, we make the scripts fully portable. For instance, a call of the form dir
path.split(os.sep) will correctly split platform-specific directory names into compo-
nents, though dirpath may look like dir\dir on Windows, dir/dir on Linux, and
dir:dir on some Macs. As mentioned, on Windows you can usually use forward slashes
rather than backward slashes when giving filenames to be opened, but these portability
constants allow scripts to be platform neutral in directory processing code.


Notice also how os.linesep comes back as \r\n here—the symbolic escape code which
reflects the carriage-return + line-feed line terminator convention on Windows, which
you don’t normally notice when processing text files in Python. We’ll learn more about
end-of-line translations in Chapter 4.


Common os.path Tools


The nested module os.path provides a large set of directory-related tools of its own.
For example, it includes portable functions for tasks such as checking a file’s type
(isdir, isfile, and others); testing file existence (exists); and fetching the size of a file
by name (getsize):


>>> os.path.isdir(r'C:\Users'), os.path.isfile(r'C:\Users')
(True, False)
>>> os.path.isdir(r'C:\config.sys'), os.path.isfile(r'C:\config.sys')
(False, True)
>>> os.path.isdir('nonesuch'), os.path.isfile('nonesuch')

92 | Chapter 2: System Tools

Free download pdf