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()
, andreadlines()
.
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.
Concepts in Practice
Opening files
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
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?
Try It
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