How to Read a Text File in Python

Python how to read a text file

Learn how to read a text file in a Python program.

For example, read a text file called example.txt into your Python program:

with open('example.txt') as file:
    lines = file.readlines()

Now lines is a variable that stores all the lines of the text file as a list of strings.

Reading Text Files in Python

Reading a text file in your Python program follows this simple procedure:

  • Open the file with the built-in open() function.
  • Read the text from the file using one of these methods: read(), readline(), readlines().
  • Close the file using the close() method. You may also want Python handle closing the file on your behalf. This is done by opening the file using the with statement.

How to Use the open() Function in Python

The basic syntax for open() function is:

open(path_to_a_file, mode)

Where:

  • path_to_a_file is the path to the file you want to open. For example Desktop/Python/example.txt. If your python program file is in the same folder as the text file, then you can use the file name only.
  • mode specifies in which state you want to open the file. There are multiple options. But as you’re interested in reading a file, you only need the mode 'r'.

With this information, you can already start reading files into your program. For instance, if you have a file called example.txt in the same folder as your program’s Python file, you can open it by:

file = open("example.txt", "r")

The File Reading Methods in Python

To actually read the file, let’s focus on the three different text reading functions next: read(), readline(), and readlines():

  • read() reads all the text from a file into a single string and returns the string.
  • readline() reads the file line by line and one by one returns each line as a single string.
  • readlines() reads the file line by line and returns the whole file as a list of strings, where each string is a line from the file.

In Python, an opened file remains open as long as you don’t close it. So make sure to always close the file. This can be done with the close() method. This is important because the program can crash or the file can corrupt if left hanging opened.

file.close()

You can also let Python take care of closing the file by using the with statement when dealing with files. In this case, you don’t need the close() method at all.

The with statement structure looks like this:

with open(path_to_file) as file:
    #action

This is a completely valid approach to handle files, so let’s stick with that for this tutorial.

Examples of Reading Files in Python

To repeat the following examples, create a folder with:

  • A reader.py file for reading text files.
  • An example.txt file from where your program reads the text.


How toRead a File Line by Line in Python

Let’s go through each file reading method of Python one by one with examples.

How to Use the read() Method in Python

To read the whole example file to a single string, use the read() method as follows:

with open('example.txt') as file:
    contents = file.read()
    print(contents)

Output:

Hi
This is just an example
I demonstrate reading lines


How to Use the readline() Method in Python

To read the file line by line by retrieving only one line at a time, use the readline() method in conjunction with a while loop as follows:

with open('example.txt') as file:
     next_line = file.readline()
     while next_line:
         print(next_line)
         next_line = file.readline()

Output:

Hi

This is just an example

I'm demonstrate reading lines

How to Use the readlines() Method in Python

To read all the lines of the text file into a list of strings where each string is one line of the text file, use the readlines() method as follows:

with open('example.txt') as file:
    lines = file.readlines()
    line_num = 0
    for line in lines:
        line_num += 1
        print("line {}: {}".format(line_num, line))  

Output:

line 1: Hi

line 2: This is just an example

line 3: I'm demonstrate reading lines

A Convenient Way to Read a File Line by Line in Python

You just saw three different ways to read a file into your Python program.

It is good to keep in mind that the open() function returns an iterable object. This means that you can loop through the file just like you’d loop a list. This makes it possible to read a file line by line using a for loop, which is a really nice approach for this task.

For example:

with open('example.txt') as file:
     for line in file:
         print(line.strip())

Output:

Hi
This is just an example
I'm demonstrate reading lines

Conclusion

Reading files into your Python program is straightforward:

  • Use the open() function with the 'r' mode to open a text file.
  • Use one of these reader methods: read()readline(), or readlines() to read the file.
  • Close the file after reading it using the close() method or let Python do it automatically by using the with statement.

Thanks for reading. Happy coding!

Further Reading

Python—How to Write to a File

10 Useful Python Snippets to Code Like a Pro

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.