Chapter 4. Files
Introduction
Credit: Mark Lutz, author of Programming Python, co-author of Learning Python
Behold the file—one of the first things that any reasonably pragmatic programmer reaches for in a programming language’s toolbox. Because processing external files is a very real, tangible task, the quality of file-processing interfaces is a good way to assess the practicality of a programming tool.
As the examples in this chapter attest, Python shines here too. In
fact, files in Python are supported in a variety of layers: from the
built-in open function’s standard
file object, to specialized tools in standard library modules such as
os, to third-party utilities available on the Web.
All told, Python’s arsenal of file tools provides
several powerful ways to access files in your scripts.
File Basics
In
Python, a file object is an instance of a built-in
type. The built-in function
open
creates and returns a file object. The first argument, a string,
specifies the file’s path (i.e., the filename
preceded by an optional directory path). The second argument to
open, also a string, specifies the mode in which
to open the file. For example:
input = open('data', 'r')
output = open('/tmp/spam', 'w')open accepts a file path in which directories and
files are separated by slash characters
(/), regardless of the
proclivities of the underlying operating system. On systems that
don’t use slashes, you can use a backslash character
(\) instead, but there’s no real reason to do so. Backslashes ...