How to Print the Contents of a File in Python?

In this tutorial, I will explain how to print the contents of a file in Python. As a developer working on various projects, I came across a scenario where I needed to print the content of a file, which made me explore more about this topic. I will cover different methods to read and print file contents, providing practical and relevant examples.

File Handling in Python

Before we get into printing file contents, let’s briefly cover the basics of file handling in Python. Python provides built-in functions to open, read, and write files. The primary functions you need to know are:

  • open(): Opens a file and returns a file object.
  • read(): Reads the entire content of a file.
  • readline(): Reads a single line from a file.
  • readlines(): Reads all lines and returns them as a list.
  • write(): Writes a string to a file.
  • close(): Closes the file.

Read How to Write to a File Without Newline in Python?

Open a File

To open a file, you use the open() function, which requires the file path and the mode in which you want to open the file. The mode can be:

  • 'r': Read (default)
  • 'w': Write (creates a new file or truncates an existing file)
  • 'a': Append (adds to the end of the file)
  • 'b': Binary mode
  • 't': Text mode (default)

Here’s an example of opening a file in read mode:

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

Check out How to Delete a File if it Exists in Python?

Close a File

It’s important to close a file once you’re done with it to free up system resources:

file.close()

Print the Contents of a File in Python

Now, let’s explore different methods to print the contents of a file in Python.

Read How to Write Lines to a File in Python?

Method 1: Use read() Method

Python read() method reads the entire content of a file and returns it as a string. This method is simple and useful for small files.

def read_file_content(file_path):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        return f"The file '{file_path}' does not exist."

file_path = 'example.txt' 
file_content = read_file_content(file_path)
print(file_content)

I expected the above example code and added the screenshot below.

Print the Contents of a File in Python

In this example, we use a try-except block to handle the case where the file does not exist. The with statement ensures that the file is properly closed after its suite finishes.

Read How to Write Multiple Lines to a File in Python?

Method 2: Use deadline() Method

Python readline() method reads one line at a time, which is useful for processing large files where you don’t want to load the entire file into memory.

def read_file_line_by_line(file_path):
    try:
        with open(file_path, 'r') as file:
            while True:
                line = file.readline()
                if not line:
                    break
                print(line, end='')
    except FileNotFoundError:
        print(f"The file '{file_path}' does not exist.")
file_path = 'example.txt'  
read_file_line_by_line(file_path)

I expected the above example code and added the screenshot below.

How to Print the Contents of a File in Python

In this example, end='' is used in the print function to avoid adding extra newlines.

Check out How to Get File Name Without Extension in Python?

Method 3: Use readlines() Method

Python readlines() method reads all the lines of a file and returns them as a list. You can then iterate over this list to print each line.

def read_all_lines(file_path):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            for line in lines:
                print(line, end='') 
    except FileNotFoundError:
        print(f"The file '{file_path}' does not exist.")

file_path = 'example.txt' 
read_all_lines(file_path)

I expected the above example code and added the screenshot below.

Print the Contents of a File in Python readlines()

Read How to Check if a File is Empty in Python?

Method 4: Use a Loop

You can also use a simple loop to iterate over the Python file object, which is memory-efficient and concise.

def read_file_efficiently(file_path):
    try:
        with open(file_path, 'r') as file:
            for line in file:
                print(line, end='')
    except FileNotFoundError:
        print(f"The file '{file_path}' does not exist.")

file_path = 'example.txt' 
read_file_efficiently(file_path)

I expected the above example code and added the screenshot below.

Print the Contents of a File in Python loop

Check out How to Rename Files in Python?

Example: Print a File with City Names

Let’s consider a practical example where we have a file named cities.txt that contains a list of city names in the USA. We’ll demonstrate how to print the contents of this file using the methods discussed above.

Example File: cities.txt

New York
Los Angeles
Chicago
Houston
Phoenix
Philadelphia
San Antonio
San Diego
Dallas
San Jose

Use read()

def print_cities_with_read():
    file_path = 'cities.txt'
    print_file_contents(file_path)

Use deadline()

def print_cities_with_readline():
    file_path = 'cities.txt'
    print_file_line_by_line(file_path)

Use readlines()

def print_cities_with_readlines():
    file_path = 'cities.txt'
    print_file_using_readlines(file_path)

Use a Loop

def print_cities_with_loop():
    file_path = 'cities.txt'
    print_file_with_loop(file_path)

Check out How to Overwrite a File in Python?

Handle Large Files

When dealing with large files, it’s important to use memory-efficient methods. The loop method is particularly useful in such cases because it reads one line at a time without loading the entire file into memory.

def print_large_file(file_path):
    try:
        with open(file_path, 'r') as file:
            for line in file:
                print(line, end='')
    except FileNotFoundError:
        print(f"The file at {file_path} does not exist.")

Conclusion

In this article, I explained how to print the contents of a file in Python. I discussed what is file handling and how to open and close a file. I covered four important methods to print the content of a file such as read() method, deadline() method, readlines() method, and using a loop.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.