Read a file in Python

problem

You’re learning Python and wish to use the file system in your program. With files we can retrieve information from our machine, load it in our program and manipulate it as we like. With a file we can persist data.

SOLUTION

Let’s suppose we have the following text file.

sample.txt
				
					Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.
Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.
A small river named Duden flows by their place and supplies it with the necessary regelialia.
It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life.
One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

				
			

We would like to write a program that will read the contents of the file and print them on the output console.

running

In Python, we can use the built-in function open() that handles files. For example:

read_file.txt
				
					file = open("sample.txt", "r") #open file for reading
contents = file.read() #read whole file as string
print(contents) # print the contents
file.close() #done, close the file

				
			

At line 1, we pass 2 parameters:

  • The file path of the file (needs to be in the same directory with the read_file.py in this case)
  • The file mode to open the file, in this case “r” which means for reading

On the next line, we read all the contents as a string and assign them to a variable and then print the variable.

When dealing with files, we follow a simple step by step approach:

  1. open the file
  2. do something with the file, read contents, read line by line, etc
  3. close the file

We always close the file, to clean up memory and for safety; to avoid memory leaks.

output
read a file in Python

The contents of the text file are printed on the console output.

conclusion

In this post we saw how to open a file for reading using Python. There are more file modes for accomplishing different tasks like writing to a file or appending.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

4.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x