python logo

How to Read a File in Python

Python hosting: Host, run, and code Python in the cloud!

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:
Python Programming Bootcamp: Go from zero to hero

Read file

The Python programming language provides the ability to work with files using open().

Python programming treats some files as text files, where lines are separated by newline characters \n. You can open regular files with the paramater r.

Other files are considered binary and can be handled in a way that is similar to the C programming language. They need to be opened with the parameters rb.

read file into string

This is a sample program that shows how to read data from a file.

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

Create python script. Open editor of your choice and create new python script. Then paste the following code.

f = open("file.txt","r")
lines = f.readlines()
print(lines)

The read method readlines() reads all the contents of a file into a string.

Save the file with name example.py and run it.

read file line by line

To output line by line, you can use a for loop. The lines may include a new line character \n, that is why you can output using endl="".

f = open("filename.txt","r")
lines = f.readlines()

for line in lines:
print(line, end="")

Another option is to remove the newline characters with the replace() method.

f = open("test.py","r")
lines = f.readlines()

for line in lines:
line = line.replace("\n","")
print(line)

read file with keyword

The with keyword can be used to read files too. This automatically closes your file.

#!/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)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

BackNext





Leave a Reply:




Stan Thu, 04 Jun 2015

So what is the writing mode for r+ ?

Frank Thu, 04 Jun 2015

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

Mohit Shukla Thu, 25 Jun 2015

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

Frank Thu, 25 Jun 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

Jahir Garcia Mon, 06 Jul 2015

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

Frank Mon, 06 Jul 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/

Christian Ransom Mon, 27 Jul 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.

Frank Mon, 27 Jul 2015

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

Ian Sat, 22 Aug 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.)

Frank Sat, 22 Aug 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.

Bruce Sun, 23 Aug 2015

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

Frank Sun, 23 Aug 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.

Joe Bauer Sun, 21 Feb 2016

Nice tuts, thanks for this.