Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo
Introduction to Python Programming

14.1 Reading from files

Introduction to Python Programming14.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.

Checkpoint

Opening a file

Concepts in Practice

Opening files

1.
What is the correct way to open a file named firstfile.txt so that the file's contents can be read into a Python program?
  1. open("firstfile")
  2. open("firstfile.txt")
  3. fileobj = open("firstfile.txt")
2.
Suppose that there is no file named input.txt. What is the result of trying to execute open("input.txt")?
  1. Error
  2. nothing
  3. "input.txt" file is created.
3.
What is the result of the following code?
fileobj = open("newfile.txt")
print(fileobj)
  1. Error
  2. Information about the object fileobj is printed.
  3. The contents of newfile.txt are printed.

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.

Example 14.1

Using read() and readlines()

A file called input.txt has the following contents:

    12
    55
    5
    91
    """Demonstrating read() and readlines()"""

    # Using read()
    # Open the file and associate with a file object
    infile = open("input.txt")

    # Read the contents of the file into a string
    str1 = infile.read()

    # Print str1
    print("Result of using read():")
    print(str1)

    # Always close the file once done using the file
    infile.close()
    
    # Using read()
    # Open the file and associate with a file object
    infile2 = open("input.txt")

    # Read the contents of the file into a string list
    str_list = infile2.readlines()

    # Printing the third item in the string list.
    print("Result of using readlines() and printing the third item in the string list:")
    print(str_list[2])

    # Always close the file once done using the file
    infile2.close()

The code's output is:

    Result of using read():
    12
    55
    5
    91
    Result of using readlines() printing the third item in the string list:
    5

Checkpoint

read() and readline()

Concepts in Practice

Reading files

Suppose fileobj = open("input.txt") has already been executed for each question below.

input.txt:

    Hello world!
    How are you?
4.
What is the correct way to use the read() function to read the contents of input.txt into a string file_str?
  1. file_str = read(fileobj)
  2. file_str = read("input.txt")
  3. file_str = fileobj.read()
5.
What is the correct way to use the readlines() function?
  1. file_lines = readlines(fileobj)
  2. file_lines = fileobj.readlines()
6.
What is printed as a result of executing print(fileobj.readline())?
  1. The first line of input.txt is printed.
  2. The contents of the file input.txt are printed.
  3. Error

Try It

Reading from a file

Open the file test.txt and print the file's contents.

Try It

Reading from a file line by line

The file input.txt is shown. The file represents a set of integers. Line 1 of the file specifies how many integers follow. Write a program that reads from this file and determines the average of the numbers following the first line.

input.txt

    n: 5
    25
    13
    4
    6
    19
Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.