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.

Video: Read files

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.