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 any other accessibility standard. Every page is built against an automated accessibility gate, and our target for the published editions is WCAG 2.2 Level AA. If something is unusable, please tell us.