How to Read Text File in Python

In this tutorial, we will learn how to read a text file in Python with the help of examples. After writing data or content into a file, we probably need to read it.

Python offers mainly three types of read functions to read data from a file. They are as:

  • read()
  • readline()
  • readlines()

But before we can read data from a file using Python code, we must need to open a file in a read access mode. Opening a file is the first step, where we specify the file path and mode.

Python provides a built-in open() function that allows us to do this. This function takes two arguments: file path and access mode. The file path can be either an absolute path or a path relative to the current directory. The general syntax to open a text file in Python is as:

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

In this code, example.txt is the name of the file that we want to open and r is the access mode in which we are opening the file. The access mode tells Python what we want to do with the file. The access mode ‘r’ is used for reading, ‘w’ is used for writing, ‘a’ is for appending, and ‘x’ is for creating a new file.

We can also add an access mode ‘b’ to open the file in binary mode rather than text mode. The open() function returns zero if the file does not exist when we open it for reading mode.

Reading a Text File in Python


Once the file is opened in the read access mode ‘r’, we can have several methods to read data from a text file. The first method to read data from a file is by using a built-in read() function provided by Python. This method is straightforward and best suited for situations where we want to read the entire contents from a file by default.

The read() function reads the data or contents of the entire file as a single string when it is opened in either the read (‘r’) mode or binary (‘rb’) mode. However, we can also specify how many characters or bytes (in binary mode) to read, by passing an argument to the read() function. The general syntax for this function is as:

file_object.read(size)

In the above syntax, the argument size is an integer value specifying the number of characters (in text mode) or bytes (in binary mode) to read from a file starting from the beginning. The read() function returns contents of the file as a string or bytes object. If the size is omitted or negative, the entire content of the file will be read and returned.

Step-by-Step Guide to Open and Read Entire Contents of a Text File

Here’s a step-by-step guide to open and read a text file in Python with complete example code.

Step 1: Prepare Your Text File

First, we must have a text file to read. Let’s create a text file named example.txt in a notepad and placed in the same directory as our Python script. The content of example.txt file might look something like this:

Hello, Python readers!
This is an example of reading a text file.
Welcome to file handling in Python.

Step 2: Writing the Python Code to Read the File

Next, open your Python editor PyCharm and create a new Python file with a specifying name. Before using the read() function, you need to open the desired file using the open() function. This function returns a file object which is then used to call the read() function. Look at the complete code below step by step.

# Open the file in read mode
file = open('example.txt', 'r')

# Read the entire content of the file.
content = file.read()

# Print the content.
print(content)

# Close the file.
file.close()

After reading from the file, it’s a good practice to close it using the close() function to free up system resources.


Step 3: Running Script Code

When you will execute this script code, you will get the following output on the console.

Output:
      Hello, Python readers!
      This is an example of reading a text file.
      Welcome to file handling in Python.

Using with Statement


However, the above script code works fine for reading files. But, it’s recommended to handle file operations using the with statement. This approach automatically takes care of opening and closing the file, even if an error occurs during file operations. Here’s how we can achieve the same result with the with statement:

# Using the with statement to open and read the file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

This method of reading files is simple and effective that allows us to quickly access and manipulate file content within your Python scripts.

Reading a Specific Size Data from a Text File


We can also read a specific number of characters or a specific size of contents from the file using read(size) function. In this function, we need to pass an integer to the size parameter. Let us take an example in which we will read a specific size of contents from a text file.

Example 2:

# Using the with statement to open and read the file
with open('example.txt', 'r') as file:
  # Read the first 52 characters of the file
    content = file.read(52)
    print(content) # Display contents on the console.
Output:
       Hello, Python readers!
       This is an example of reading a text file.

Checking the Existence of File Using os.path Module


Sometimes, we need to check the data file availability in the working folder. For example, we write the file name “exampl.txt” instead of “example.txt” in the above code, the program will raise an error as given below:

Traceback (most recent call last):
  File "C:\Python Project\FileHanlding\Reading.py", line 2, in 
    with open('exampl.txt', 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'exampl.txt'

Therefore, to avoid such as error, we need to import os module and use os.path.isfile(file_path). The os.path module in Python offers a isfile() function that is used to check an existing file is on the specified path or not.

This function is especially useful for verifying the existence of a file on a specified path before attempting file operations, such as opening or reading the file. The syntax of the isfile() function is quite straightforward:

os.path.isfile(path)

In the above syntax, the argument path is a string representing the path that we want to verify as a file. It returns 1 (True) if the file is present on the specified path, and 0 if the file does not exist.

How to Use isfile() Function?

To use the isfile() function, we first need to import the os.path module. Here’s a simple example that checks whether a file “exampl.txt” exists or not on the specified path.

Example 3:

# Importing the os.path module.
import os.path
txtfile = "exampl.txt" # text file is assigned.
# Checking the file exists or not.
if os.path.isfile(txtfile):
        with open(txtfile, 'r') as file:
            content = file.read()
            print(content)
else:
    print(f"The file {txtfile} does not exist on the specified file path.")
Output:
       The file exampl.txt does not exist on the specified file path.

This code snippet checked that the file “exampl.txt” does not exist on the specified path and printed a message.

How to Read a Text File in Python Line by Line?


Reading the contents from a file line by line is a common task in programming, especially when dealing with text files that contain structured data, like logs or configuration files. For this, Python provides a built-in readline() function that reads data from a file line by line.

This function read a single line from the file each time it is called. For instance, the first call to readline() returns the first line, the second call returns the second line, and so on. The basic syntax of the readline() function is as follows:

fileobject.readline(n)

In the above syntax, fileobject is the name of the file object returned by the open() function when you open a file. An optional integer argument n specifies the maximum number of bytes to be read from the line. In other words, it allows us to read up to n characters from the current line, rather than the entire line.

The readline() function returns a string that contains the next line from the file, including the newline character (\n) at the end, if present. When the end of the file is reached, the readline() returns an empty string.

Let us take the previous example in which we have created a file named “example.txt”. Now, we will read the first line using readline() function.

Example 4:

# Open the text file in read mode.
with open('example.txt', 'r') as file:
        # Read the next line
        line = file.readline()
        # Print the line
        print(line, end='')
Output:
       Hello, Python readers!

To read all lines from a file using readline() method, we will use while loop. Look at the example code below.

Example 5:

txtfile = "example.txt"
# Open the text file in read mode.
try:
  with open(txtfile, 'r') as file:
    while True:
        # Read the next line
        line = file.readline()
        # If line is empty, end of file is reached
        if not line:
            break
        # Print the line
        print(line, end='')
except IOError:
  print("There is no file named", txtfile)
Output:
       Hello, Python readers!
       This is an example of reading a text file.
       Welcome to file handling in Python.

Note that when the readline() function reaches the end of the file, it returns an empty string. Else, it returns the line of text including, a newline character. In the statement print(line, end=”), we have used a separator end=” to avoid the blank line.

Reading All Lines Data from Text File in Python


We can also read all line data from a text file in Python using readlines() function. The built-in readlines() function provided by Python returns a list of lines from the file till the end of the file (EOF). This method reads all rows and retains a newline character (‘\n’) at the end of every row.

The readlines() method provides a convenient way to read and store the entire contents of a file in a list form, making it easy to manipulate or iterate over each line of the file subsequently. The basic syntax of readlines() function in Python is as:

fileobject.readlines([size])

Here, the parameter size is an optional parameter. If we specify a value, it reads the approximate number of bytes or characters from the file and returns the lines from the file. Let’s take an example program in which we will read data from “student.txt” file using readlines() function.

Example 6:

txtfile = "studentinfo.txt"
try:
  # Open a file for reading mode.
  with open(txtfile, 'r') as file:
    # Read all lines into a list.
    student = file.readlines() # reads all lines
    print("Student information: ")
    
  # Iterate over the list and print each line
  for line in student:
    print(line, end='')  # end='' is used to avoid adding extra newline characters
except IOError:
  print("There is no file named", txtfile)
Output:
       Student information:
       Amit Kumar, RSVM, Dhanbad
       Tripti Priya, DPS, Dhanbad
       Mahika Kumari, DAV, Dhanbad
       Ivaan Sagar, DPS, Pune
       Rashmi Kumari, SSLNT, Dhanbad

In this example, we open example.txt for reading, use readlines() function to read all lines into a list named student. Then, we iterate over this list to print each line.

Reading Data without File Handling Methods


We can also read data from a file without using file handling methods like read(), readline(), or readlines(). One of the simplest and most efficient ways to read a file line by line in Python is by iterating over the file object directly using a for loop.

When we open a file for reading in read mode, it returns an iterable object that automatically reads lines one at a time when iterated over. Let us take an example on it.

Example 7:

txtfile = "example.txt"
try:
  # Open the file using the with statement
  with open('example.txt', 'r') as file:
    # Iterate over each line in the file
    for line in file:
      # Print the line (end='' prevents adding an extra newline)
      print(line, end='')
except IOError:
  print("There is no file named", txtfile)
Output:
       Hello, Python readers!
       This is an example of reading a text file line by line using a for loop.
       Welcome to file handling operation in Python.

In this tutorial, we have learnt step by step how to read a text file in Python using file handling methods like read(), readline(), and readlines(). Hope that you will have understood the basic concepts of reading data from a text file and practiced all example programs.
Thanks for reading!!!