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.
13.1. Opening files and file objects
In Python, you open and read a file 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:
file_object = open('myfile', 'r') line = file_object.readline()
open doesn’t read anything from the file; instead it returns an object called a file ...
Get The Quick Python Book, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.