Prévia do material em texto
326 13 • Inheritance
Access for free at openstax.org
Figure 14.1 credit: Larissa Chu, CC BY 4.0
Chapter Outline
14.1 Reading from files
14.2 Writing to files
14.3 Files in different locations and working with CSV files
14.4 Handling exceptions
14.5 Raising exceptions
14.6 Chapter summary
Introduction
Programming often involves reading information from files and writing information into files. This chapter
begins by introducing how to read from and write into files in Python.
Reading and writing files can lead to exceptions when the file specified cannot be found. There are many other
situations in which exceptions can occur. The second half of the chapter introduces exceptions and how to
handle exceptions in Python.
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.
Files
14
CHECKPOINT
Opening a file
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
14-1-reading-from-files)
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?
a. open("firstfile")
b. open("firstfile.txt")
c. 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")?
a. Error
b. nothing
c. "input.txt" file is created.
3. What is the result of the following code?
fileobj = open("newfile.txt")
print(fileobj)
a. Error
b. Information about the object fileobj is printed.
c. 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
328 14 • Files
Access for free at openstax.org
https://openstax.org/books/introduction-python-programming/pages/14-1-reading-from-files
https://openstax.org/books/introduction-python-programming/pages/14-1-reading-from-files
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
14.1 • Reading from files 329
CHECKPOINT
read() and readline()
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
14-1-reading-from-files)
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?
a. file_str = read(fileobj)
b. file_str = read("input.txt")
c. file_str = fileobj.read()
5. What is the correct way to use the readlines() function?
a. file_lines = readlines(fileobj)
b. file_lines = fileobj.readlines()
6. What is printed as a result of executing print(fileobj.readline())?
a. The first line of input.txt is printed.
b. The contents of the file input.txt are printed.
c. Error
TRY IT
Reading from a file
Open the file test.txt and print the file's contents.
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
14-1-reading-from-files)
330 14 • Files
Access for free at openstax.org
https://openstax.org/books/introduction-python-programming/pages/14-1-reading-from-files
https://openstax.org/books/introduction-python-programming/pages/14-1-reading-from-files
https://openstax.org/books/introduction-python-programming/pages/14-1-reading-from-files
https://openstax.org/books/introduction-python-programming/pages/14-1-reading-from-files
Chapter 14 Files
Introduction
14.1 Reading from files