How to read a text file in Python – with example

  • Reading time:15 mins read

How to read a text file in Python?

The management of resources such as text files or database connections is a very important aspect of any programming language. Now reading and writing files is something that is done very often when writing programs in Python or any other programming language. More often these files are in common formats such as CSV, text file, JSON etcetera. In this article, you’ll learn how to read a text file in Python.

 

How to read a text file in Python – Main methods

Every programming language provides unique ways of handling resources such as text files. In python there are a couple of ways of handling resources, these include the use of the inbuilt keyword open(). The syntax of using the keyword open() is as shown below.

 

f.open("sample.txt", encoding = 'uft-8')

#file operations

f.close()

 

File handling within a try-except block

While this method works just fine it is not guaranteed that the files will be closed after their usage, especially if an exception occurs while performing file operations. When working with large programs more often than not several files may be involved, in such scenarios we need to make sure that files are properly closed.

 

How to read a text file in Python

 

This is the best way of building efficient programs that minimize the usage of computer resources such as memory.  Exceptions while performing file operations can be safely handled by wrapping the open() function with a try and catch block. As shown below.  

 

try:
f = open('sample.txt', encoding = 'utf - 8')
#file operations
finally:
f.close()

 

Although this method ensures that files are properly closed even when there is an exception, the best way to open and close files is by using the context manager. Using the context manager guarantees that files will be closed even if there is an exception and the program is forced to terminate prematurely.

Furthermore, we do not need to explicitly define the close method since files are closed automatically. The context manager is made up of two main keywords with and the function open().

This function accepts quite a number of arguments, however, the two main arguments include the name of the file that we intend to open and the mode that we want to open it. We are also going to open the file as f followed by a full colon.

 

How to read a text file in Python

How to read a text file in Python – Using the read method

Once we hit the enter button, we realise that we have an indention, we are now within the context manager. Now within this context manager we need to initialize the method read() as follows data = f.read(). This method allows us to read all characters from a file until the end.  

 

 

The contents of the text file can be seen in the terminal once we execute the code. Therefore, we have successfully opened the file using the context manager.

And as seen in the code above we need not worry about closing the file since the context manager handles that automatically.

Alternatively, since the variable data is already initialized, we don’t have to stay within the confines of the context manager. Therefore once the variable is initialized we can also print it out of the context manager and still get the same result.  

Opening and closing files in Python using the context manager is considered good practice since it is not only efficient but also very flexible.

Summary

This is how to read a text file in Python in practice. If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.

In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.

Programming tutorials

Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.

Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING

Not sure if programming is for you? With CodeBerry you’ll like it.