Skip to Content
The Quick Python Book, Third Edition
book

The Quick Python Book, Third Edition

by Naomi Ceder, David Fugate
May 2018
Beginner
472 pages
15h 3m
English
Manning Publications
Content preview from The Quick Python Book, Third Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Think Python, 3rd Edition

Think Python, 3rd Edition

Allen Downey
Learn Python Programming - Third Edition

Learn Python Programming - Third Edition

Fabrizio Romano, Heinrich Kruger

Publisher Resources

ISBN: 9781617294037Publisher SupportOtherPublisher WebsiteSupplemental ContentErrata PagePurchase Link