Skip to main content
Engineering LibreTexts

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}\)
    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 \(\PageIndex{1}\): Opening files

    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")
    Answer

    c. The file is opened and is associated with the fileobj object. Reading from the file will be possible using fileobj.

    Concepts in Practice \(\PageIndex{2}\): Opening files

    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.
    Answer

    a. The file must exist in the same folder as the Python file in order for the file to be opened.

    Concepts in Practice \(\PageIndex{3}\): Opening files

    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.
    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.
    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?
    
    Concepts in Practice \(\PageIndex{4}\): Reading files

    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()
    Answer

    c. The read() function is called on fileobj. The file's contents will be read into file_str.

    Concepts in Practice \(\PageIndex{5}\): Reading files

    What is the correct way to use the readlines() function?

    1. file_lines = readlines(fileobj)
    2. file_lines = fileobj.readlines()
    Answer

    b. The readlines() function is called on fileobj. file_lines is the string list ['Hello world!\n', 'How are you?\n'].

    Concepts in Practice \(\PageIndex{6}\): Reading files

    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
    Answer

    a. The readline() function reads the next line of a file. Since readline() is called right after opening the file the first line is read. The resulting string "Hello world!" is printed. Note that readline() includes the '\n' character so the print will include an additional newline.

    Try It: Reading from a file

    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)

    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
    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 = 0

    for 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()


    This page titled 14.1: Reading from Files is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.