How to Read a File in Python (Text and JSON)

Learn how to read files in Python. Master the with open statement, readline, readlines, and safely handling file exceptions.

Try Code in Editor

Explanation

File handling is an essential skill for any Python developer. Reading data from files allows you to process text documents, configurations, logs, databases, and structured datasets. Python makes file operations remarkably straightforward through its built-in `open()` function.

When working with files, the most critical best practice is to use the `with` statement, which creates a context manager. The `with open(...)` pattern guarantees that the file is safely and properly closed as soon as execution leaves the block, even if an exception occurs inside. Forgetting to close files can cause memory leaks, file corruption, and lock resources from other system processes.

Python provides several methods to read data once a file is opened. The `.read()` method returns the entire content of the file as a single string. The `.readline()` method reads a single line, making it perfect for iterating over giant files that wouldn't fit into memory. The `.readlines()` method reads all lines and returns them as a list of strings. Understanding which method to use prevents memory exhaustion and makes your programs more scalable.

Step-by-Step Implementation

  1. 1

    Use the with open("filename", "r") as file statement to safely open the file for reading.

  2. 2

    Call file.read() to load the entire file content into a variable.

  3. 3

    Iterate directly over the file object using a for loop to read it line-by-line efficiently.

  4. 4

    Always specify the encoding (e.g., encoding="utf-8") for international character compatibility.

Code Example

This script demonstrates reading file contents safely using the context manager with, line-by-line reading, and error handling.

read_file.py
Try in Editor
# Writing a dummy file first
with open("sample.txt", "w") as f:
    f.write("Line 1: Welcome to PyRun!\nLine 2: Python runs in the browser.\nLine 3: Clean and simple.")

# 1. Read entire file contents
with open("sample.txt", "r") as file:
    content = file.read()
    print("--- Entire File ---")
    print(content)

# 2. Read line-by-line (Memory efficient for large files)
print("\n--- Line by Line ---")
with open("sample.txt", "r") as file:
    for line in file:
        print("Read line:", line.strip())
Terminal Output
--- Entire File ---
Line 1: Welcome to PyRun!
Line 2: Python runs in the browser.
Line 3: Clean and simple.

--- Line by Line ---
Read line: Line 1: Welcome to PyRun!
Read line: Line 2: Python runs in the browser.
Read line: Line 3: Clean and simple.

Frequently Asked Questions

Why should I use the with statement to open files?

The with statement creates a context manager that automatically closes the file when the block is exited, even if errors occur.

How do I handle a FileNotFoundError?

Wrap your open() statement in a try-except block, catching FileNotFoundError: try: with open(...) ... except FileNotFoundError: print("File not found!").

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.