Open In App

Print the Content of a Txt File in Python

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content of a .txt file using Python.

How To Print The Content of A .Txt File In Python?

Below, is the step-by-step guide to How To Print The Content Of A .Txt File In Python.

First create a one File .txt in same folder where your .py file is located or add the file path.

Example 1: Using the open() & read() Functions

In this example, we use the open() function to open the file in read mode (‘r’). The file is then read using the read() function, and its content is stored in the file_content variable. Finally, we print the content to the console. We have also included error handling to manage cases where the file is not found or if any other exception occurs during the execution.

Python3




# Open the file in read mode
file_path = 'sample.txt'
 
try:
    with open(file_path, 'r') as file:
        # Read the content of the file
        file_content = file.read()
         
        # Print the content
        print("File Content:\n", file_content)
 
except FileNotFoundError:
    print(f"File '{file_path}' not found.")
except Exception as e:
    print(f"An error occurred: {e}")


Output

File Content:
GeeksforGeeks is best Coding Platform .

Example 2: Using with statement & readlines() Method

In this example, we use the readlines() method to read the file line by line. The lines are then stored in the file_lines variable, and we use a loop to print each line to the console. The strip() method is used to remove any trailing newline characters. As in the first example, error handling is included to handle file not found or other exceptions.

Python3




# Open the file in read mode
file_path = 'sample.txt'
 
try:
    with open(file_path, 'r') as file:
        # Read the lines of the file
        file_lines = file.readlines()
 
        # Print each line
        print("File Content:")
        for line in file_lines:
            print(line.strip())
 
except FileNotFoundError:
    print(f"File '{file_path}' not found.")
except Exception as e:
    print(f"An error occurred: {e}")


Output

File Content:
GeeksforGeeks is best Coding Platform .

Conclusion

Printing the content of a .txt file in Python is a straightforward task, and you can choose the method that best suits your needs. The open() function and its variations, combined with methods like read() and readlines(), provide powerful tools for working with file content. Whether you are dealing with small or large text files, these examples should help you get started with reading and printing file contents in Python.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads