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.
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 – 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
- How to use the Python for loop
- How to use Python Sets
- How to use a Python Dictionary
- How to use Python Classes
- How to use Python Range
- How to use Python if-else statements
- How to use Python RegEx
- How to use Python Lists
- How to use Python Enumerate
- How to use Python Functions
- How to use Python Split
- How to use Python Try-Except
- How to use Python Tuples
- How to use Python Arrays
- How to use Python Sort
- How to use the Python DateTime
- How to download Python?
- How to use the Python FileWrite function
- How to use Python Lambda
- How to use Python ListAppend
- How to use Python ListComprehension
- How to use Python Map
- How to use Python Operators
- How to use Python Pandas
- How to use Python Requests
- How to use Python Strings
- How to use Python Count
- How to use Python Comments
- How to use the Python File Reader method
- How to use the Python IDE-s
- How to use Python logging
- How to use Python Print
- How to use the Python Zip
- How to use Python Append
- How to use Python Global Variables
- How to use the Python join method
- How to use Python list length
- How to use Python JSON files
- How to use Python Modulo
- How to use Python file opening methods
- How to use Python round
- How to use Python sleep
- How to use Python replace
- How to use Python strip
- How to use the Python Time module
- How to use Python unittests
- How to save data to a text file using Context Manager?
- How to use Python external modules
- How to use Python find
- How to install the Python pip package manager
- How to delete files in Python
- Parsing XML files in Python
- How to make a GUI in Python
- How to use Python in Command Prompt
- How to Run a Python Program in VS Code
- How to run a program in Python IDLE
- How to run a program in Jupyter Notebook
- How to read a text file in Python
- How to add numbers in Python
- How to ask for user input in Python
- How to debug in Python
- How to create a thread in Python
- How to import a library in Python
- How to use the PIP package manager
- How to use classes in Python
- How to reverse strings in Python
- How to convert a string to int in Python
- How to print on the same line in Python
- How to remove items from a list
- How to add to a dictionary in Python
- How to raise an exception in Python
- How to throw an exception in Python
- How to stop a program in Python
- How to use Python assert
- How to use the Python compiler
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.
