预计阅读本页时间:-
Other File Tools
There are additional, more advanced file methods shown in Table 9-2, and even more that are not in the table. For instance, as mentioned earlier, seek resets your current position in a file (the next read or write happens at that position), flush forces buffered output to be written out to disk (by default, files are always buffered), and so on.
The Python standard library manual and the reference books described in the Preface provide complete lists of file methods; for a quick look, run a dir or help call interactively, passing in an open file object (in Python 2.6 but not 3.0, you can pass in the name file instead). For more file-processing examples, watch for the sidebar Why You Will Care: File Scanners. It sketches common file-scanning loop code patterns with statements we have not covered enough yet to use here.
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Also, note that although the open function and the file objects it returns are your main interface to external files in a Python script, there are additional file-like tools in the Python toolset. Also available, to name a few, are:
Standard streams
Preopened file objects in the sys module, such as sys.stdout (see Print Operations)
Descriptor files in the os module
Integer file handles that support lower-level tools such as file locking
Sockets, pipes, and FIFOs
File-like objects used to synchronize processes or communicate over networks
Access-by-key files known as “shelves”
Used to store unaltered Python objects directly, by key (used in Chapter 27)
Shell command streams
Tools such as os.popen and subprocess.Popen that support spawning shell commands and reading and writing to their standard streams
The third-party open source domain offers even more file-like tools, including support for communicating with serial ports in the PySerial extension and interactive programs in the pexpect system. See more advanced Python texts and the Web at large for additional information on file-like tools.
Note
Version skew note: In Python 2.5 and earlier, the built-in name open is essentially a synonym for the name file, and files may technically be opened by calling either open or file (though open is generally preferred for opening). In Python 3.0, the name file is no longer available, because of its redundancy with open.
Python 2.6 users may also use the name file as the file object type, in order to customize files with object-oriented programming (described later in this book). In Python 3.0, files have changed radically. The classes used to implement file objects live in the standard library module io. See this module’s documentation or code for the classes it makes available for customization, and run a type(F) call on open files F for hints.