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 ...
Get The Quick Python Book, Third 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.