Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

14.1 Reading from files

Learning objectives

By the end of this section you should be able to

  • Understand how to open a file using the open function.
  • Demonstrate how to read information from a file using read, readline, and readlines.

Opening a file

Reading information from and writing information to files is a common task in programming.

Python supports the opening of a file using the open function.

Using read and reading lines

Python provides functions that can be called on a file object for reading the contents of a file:

  • The read function reads the contents of a file and returns a string.
  • The readline function reads the next line in a file and returns a string.
  • The readlines function reads the individual lines of a file and returns a string list containing all the lines of the file in order.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.