File Tools
External files are at the heart of much of what we do with shell utilities. For instance, a testing system may read its inputs from one file, store program results in another file, and check expected results by loading yet another file. Even user interface and Internet-oriented programs may load binary images and audio clips from files on the underlying computer. It’s a core programming concept.
In Python, the built-in open
function is the primary tool scripts use to access the files on the
underlying computer system. Since this function is an inherent part of
the Python language, you may already be familiar with its basic
workings. Technically, open gives
direct access to the stdio
filesystem calls in the system’s C library—it returns a new file
object that is connected to the external file and has methods that map
more or less directly to file calls on your machine. The open function also provides a portable
interface to the underlying filesystem—it works the same way on every
platform on which Python runs.
Other file-related interfaces in Python allow us to do things
such as manipulate lower-level descriptor-based files (os module), store objects away in files by
key (anydbm and shelve modules), and access SQL databases.
Most of these are larger topics addressed in Chapter 19.
In this chapter, we’ll take a brief tutorial look at the built-in file object and explore a handful of more advanced file-related topics. As usual, you should consult the library manual’s file object ...