O'Reilly logo

The Quick Python Book by Naomi R. Ceder

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required