14.1: Reading from Files
- Page ID
- 117613
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)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.
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?
open("firstfile")open("firstfile.txt")fileobj = open("firstfile.txt")
- Answer
-
c. The file is opened and is associated with the fileobj object. Reading from the file will be possible using fileobj.
Suppose that there is no file named input.txt. What is the result of trying to execute open("input.txt")?
Error- nothing
- "input.txt" file is created.
- Answer
-
a. The file must exist in the same folder as the Python file in order for the file to be opened.
What is the result of the following code?
fileobj = open("newfile.txt")
print(fileobj)
Error- Information about the object
fileobjis printed. - The contents of newfile.txt are printed.
- Answer
-
b. Python interprets this command as the programmer trying to print the object details. The object details are printed. Ex:
<_io.TextIOWrapper name='newfile.txt' mode='r' encoding='cp1252'>.
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.
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
Suppose fileobj = open("input.txt") has already been executed for each question below.
input.txt:
Hello world!
How are you?
What is the correct way to use the read() function to read the contents of input.txt into a string file_str?
file_str = read(fileobj)file_str = read("input.txt")file_str = fileobj.read()
- Answer
-
c. The
read()function is called onfileobj. The file's contents will be read intofile_str.
What is the correct way to use the readlines() function?
file_lines = readlines(fileobj)file_lines = fileobj.readlines()
- Answer
-
b. The
readlines()function is called onfileobj.file_linesis the string list['Hello world!\n', 'How are you?\n'].
What is printed as a result of executing print(fileobj.readline())?
- The first line of input.txt is printed.
- The contents of the file input.txt are printed.
Error
- Answer
-
a. The
readline()function reads the next line of a file. Sincereadline()is called right after opening the file the first line is read. The resulting string"Hello world!"is printed. Note thatreadline()includes the'\n'character so the print will include an additional newline.
Open the file test.txt and print the file's contents.
Interactive Code
- Input
-
Quoth the Raven:
"Nevermore"
3 - Answer
-
str1 = input()
str2 = input()
count = int(input())result = str1 + " " + str2 + "\n"
print(result * count)
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
Interactive Code
- Answer
-
# Open the file
infile = open("input.txt")# Read the first line and extract n from line 1
firstline_split = infile.readline().split(":")
n = int(firstline_split[1])# Read the remaining lines in the file
inlines = infile.readlines()# Initialize a variable to calculate the summation
summation = 0for i in range(n):
summation += int(inlines[i]) # Type casting to take the read string and convert to integer# Print the average
print("Average =", (summation/n))# Close the file
infile.close()


