How to Read a Text File in Python: A Step-by-Step Guide

Jacob Naryan - Full-Stack Developer

Posted: Wed Aug 09 2023

Last updated: Wed Nov 22 2023

Reading text files in Python is a fundamental skill that every Python developer should have. Despite Python’s simplicity, it provides a powerful tool for working with data, whether it’s in text files or any other format. In this blog post, I will guide you through how to read a text file in Python step-by-step.

1. Open the File

Before we can read a file, we first need to open it. This is done using the built-in open() function in Python. This function receives two parameters - the name of the file and the mode of opening.

file = open('file.txt', 'r')

In this example, 'r' signifies that we are opening the file in read mode.

2. Read the File

Once you’ve opened the file, you have a few options when it comes to reading it. Here are some of the common methods:

2.1 Reading All at Once

You can use the read() function to read all contents of the file at once.

content = file.read()
print(content)

2.2 Reading Line by Line

If you want to read a file line by line, use the readline() function.

line = file.readline()
print(line)

2.3 Reading All Lines into a List

If you want to read all lines into a list, use the readlines() function.

lines = file.readlines()
print(lines)

3. Close the File

After reading from a file, it is good practice to close it.

file.close()

This is important because it frees up resources and ensures that changes made to the file are actually saved.

4. Using ‘with’ Statement for Better Practice

While the above method works fine, there’s a better way to handle files that is cleaner and takes care of closing the file for you.

with open('file.txt', 'r') as file:
content = file.read()
print(content)

In this example, Python’s with statement is used which automatically takes care of closing the file once done with it.

And that’s it! You now know how to read a text file in Python step by step. It’s easy and intuitive, just like Python itself.

Thank you for reading. If you liked this blog, check out more of my tutorials about software engineering on my personal site here.

Thanks for reading, please consider tipping some BTC if you liked the blog!
Click or scan the QR code below.

bitcoin address for tips if you are so inclined.