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

13.1. Opening files and file 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:

with open('myfile', 'r') as file_object:
    line = file_object.readline()

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:

13.2. Closing files

13.3. Opening files in write or other modes

13.4. Functions to read and write text or binary data

13.5. Reading and writing with pathlib

13.6. Screen input/output and redirection

13.7. Reading structured binary data with the struct module

13.8. Pickling objects files

13.9. Shelving objects

Summary

sitemap