CHAPTER 4
File and Directory Tools
“Erase Your Hard Drive in Five Easy Steps!”
This chapter continues our look at system interfaces in Python by focusing on file and
directory-related tools. As you’ll see, it’s easy to process files and directory trees with
Python’s built-in and standard library support. Because files are part of the core Python
language, some of this chapter’s material is a review of file basics covered in books like
Learning Python, Fourth Edition, and we’ll defer to such resources for more back-
ground details on some file-related concepts. For example, iteration, context managers,
and the file object’s support for Unicode encodings are demonstrated along the way,
but these topics are not repeated in full here. This chapter’s goal is to tell enough of the
file story to get you started writing useful scripts.
File Tools
External files are at the heart of much of what we do with system 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. When called, the open
function returns a new file object that is connected to the external file; the file object
has methods that transfer data to and from the file and perform a variety of file-related
operations. The open function also provides a portable interface to the underlying file-
system—it works the same way on every platform on which Python runs.
Other file-related modules built into Python allow us to do things such as manipulate
lower-level descriptor-based files (os); copy, remove, and move files and collections of
files (os and shutil); store data and objects in files by key (dbm and shelve); and access
135
Do
wnload from Wow! eBook <www.wowebook.com>