Chapter 13. Reading and writing files
This chapter covers
- Opening files and file objects
- Closing files
- Opening files in different modes
- Reading and writing text or binary data
- Redirecting screen input/output
- Using the struct module
- Pickling objects into files
- Shelving objects
Probably the single most common thing you’ll want to do with files is open and read them.
In Python, you open and read a file by using the built-in open function and various built-in reading operations. The following short Python program reads in one line from a text file named myfile:
open doesn’t read anything from the file; instead, it returns an object called a file object that you can use to access the opened file. A file object keeps track of a file and how much of the file has been read or written. All Python file I/O is done using file objects rather than filenames.
The first call to readline returns the first line in the file object, everything up to and including the first newline character or the entire file if there’s no newline character in the file; the next call to readline returns the second line, if it exists, and so on.
The first argument to the open function is a pathname. In the previous example, you’re opening what you expect to be an existing file in the current working directory. The following opens a file at an absolute location—c:\My Documents\test\myfile: