Last modified: Feb 06, 2026 By Alexander Williams
Python Read File: Complete Guide for Beginners
Reading files is a core skill in Python programming. You need it to work with data.
This guide will teach you how. We will cover the basics and best practices.
You will learn to read text files, CSV files, and JSON files.
Opening a File with open()
The first step is to open the file. You use the open() function.
This function needs the file path and a mode. The mode tells Python what you want to do.
For reading, you use the mode 'r'. It stands for read.
# Open a file for reading
file_object = open('data.txt', 'r')
This code creates a file object. You can now read from it.
It is very important to close the file later. Use the close() method.
Forgetting to close can cause problems. It might lock the file or waste memory.
file_object.close() # Always close the file
The Best Way: Using 'with'
There is a safer and better way. Use the with statement.
It automatically handles opening and closing. You do not need to call close().
This method prevents errors. It is the recommended approach.
# The safe way to open a file
with open('data.txt', 'r') as file:
# Do your reading here
content = file.read()
# File is automatically closed here
The file is closed when the block ends. Even if an error occurs.
Reading the Entire File
To get all the text at once, use the read() method.
It reads everything into a single string. This is good for small files.
with open('example.txt', 'r') as f:
full_text = f.read()
print(full_text)
Imagine 'example.txt' contains three lines of text.
Hello, World!
This is line two.
And this is line three.
The output would be one string with newline characters.
Hello, World!
This is line two.
And this is line three.
Reading Line by Line
For larger files, reading line by line is better. It saves memory.
You can use a for loop directly on the file object.
This is efficient and easy to read.
with open('big_data.txt', 'r') as file:
for line in file:
print(f"Line: {line.strip()}") # strip() removes extra newlines
You can also use readline() to read one line at a time.
Or use readlines() to get all lines as a list.
with open('data.txt', 'r') as f:
first_line = f.readline() # Reads just the first line
all_lines_list = f.readlines() # Reads remaining lines into a list
Working with Different File Types
Python can read more than just plain text. You can handle CSV and JSON files easily.
Reading CSV Files
CSV files store table data. Use the built-in `csv` module.
It helps you read rows as lists or dictionaries.
import csv
with open('data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # Each row is a list of values
Reading JSON Files
JSON is common for web data and configurations. Use the `json` module.
The json.load() function reads the file and converts it to a Python dictionary.
import json
with open('config.json', 'r') as jsonfile:
data = json.load(jsonfile) # data is now a Python dictionary
print(data['setting'])
Handling Errors and File Paths
Files might not exist. Your program should handle this gracefully.
Use a try-except block with `FileNotFoundError`.
try:
with open('missing.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("Error: The file was not found.")
Also, pay attention to file paths. Use raw strings (r'path') for Windows paths with backslashes.
Or use forward slashes which work on all systems.
# Good practice for paths
file_path = r'C:\Users\Name\data.txt' # Raw string for Windows
file_path = 'data/files/info.txt' # Forward slashes are universal
Best Practices for Reading Files
Follow these tips for clean and reliable code.
Always use the with statement. It manages resources for you.
Specify the file encoding for text files. Use `encoding='utf-8'`.
This prevents errors with special characters.
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
For very large files, read in chunks. Do not use read() all at once.
Process the file line by line or in fixed-size blocks.
Conclusion
Reading files in Python is straightforward. The key function is open().
Remember to use the with statement for safety. Choose the right reading method for your task.
Use read() for small files. Use a for loop for large files.
Handle different formats like CSV and JSON with their dedicated modules.
Always include error handling. Your programs will be more robust.
Start practicing with your own text files. You will master file reading quickly.