Read file


You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.

Related Course:
Automate the Boring Stuff with Python Programming

Read file

You can read a file with the code below.

The file needs to be in the same directory as your program, if it is not you need to specify a path.

#!/usr/bin/env python
 
# Define a filename.
filename = "bestand.py"
 
# Open the file as f.
# The function readlines() reads the file.             
with open(filename) as f:
    content = f.readlines()
 
# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'. 
for line in content:
    print(line),

The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.

If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:

content = f.read().splitlines()

Resulting in this code:

#!/usr/bin/env python
 
# Define a filename.
filename = "bestand.py"
 
# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
    content = f.read().splitlines()
 
# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'. 
for line in content:
    print(line)

While the codes above work, we should always test if the file we want to open exists.  We will test first if the file does not exist, if it does it will read the file else return an error. As in the code below:

#!/usr/bin/env python
import os.path
 
# Define a filename.
filename = "bestand.py"
 
if not os.path.isfile(filename):
    print 'File does not exist.'
else:
    # Open the file as f. 
    # The function readlines() reads the file.
    with open(filename) as f:
        content = f.read().splitlines()
 
    # Show the file contents line by line.
    # We added the comma to print single newlines and not double newlines.
    # This is because the lines contain the newline character '\n'. 
    for line in content:
        print(line)

13 thoughts on “Read file

  1. Joe Bauer - February 21, 2016

    Nice tuts, thanks for this.

  2. Bruce - August 23, 2015

    Hi Frank!
    What’s the differences between with open and open?Can I use with open as f:f.write(“blah blah”)?Thanks!

    1. Frank - August 23, 2015

      The with statement executes all code in the block and closes the file automatically. File manipulations can be done inside the code block using with. If you use open you can do file operations at any time until you close the file.

  3. Ian - August 22, 2015

    Two questions:
    For the python3 replacement of the command, “print line,” is it “print(line,)” or “print(line),” ?

    Shouldn’t the file in the “Read” example, also be closed with the command, “f.close()”, or is the file automatically closed at the end of a program if it is opened with the command, “with open(filename) as f”? (Still it seems risky to leave it open longer than necessary, in case the program crashes at some later point.)

    1. Frank - August 22, 2015

      Hi Ian!

      For python3, use print(line) because print is a function. The comma between the brackets is used for tuples.
      Using “with open(filename) as f” the file will automatically be closed after the block of code has completed.

  4. Christian Ransom - July 27, 2015

    “The first part of the code will read the file contents and the second part will that line by line.”

    Typo? I don’t understand this sentence.

    1. Frank - July 27, 2015

      Thanks Christian! Yes, this is a typo. I updated it

  5. Jahir Garcia - July 6, 2015

    How to open a html file in a navigator from Python??

    1. Frank - July 6, 2015

      Hi Jahir, what do you mean by navigator? Do you mean a webbrowser?

      If you want to parse HTML look at this tutorial: https://pythonspot.com/http-parse-html-and-xhtml/.
      If you want a webbrowser to open an html file in your webbrowser, simply execute it as program: https://pythonspot.com/python-subprocess/

  6. Stan - June 4, 2015

    So what is the writing mode for r+ ?

    1. Frank - June 4, 2015

      Hi Stan, r+ opens the file for both reading and writing from the start of the file.

      1. Mohit Shukla - June 25, 2015

        and w+ appends the data to existing file, I suppose.

        1. Frank - June 25, 2015

          w+ opens for reading and writing. The file is created if it does not exist, otherwise it is truncated (data is deleted if exists). The stream is positioned at the beginning of the file. Use a+ if you want to append