Python Basics — Reading Files
Reading Files
Reading files is one of the first real-world tasks you’ll do in Python. Whether it’s log files, configuration, or data — the pattern is always the same.
The open() Function
file = open("example.txt", "r") # "r" = read mode (default)
content = file.read()
print(content)
file.close() # Always close the file!
Better approach: Use
withstatement (covered later) to handle closing automatically.
File Modes for Reading
| Mode | Description |
|---|---|
"r" |
Read text (default) |
"rb" |
Read binary (images, PDFs, etc.) |
Reading Methods
Assume sample.txt contains:
Hello World
Python is great
File handling is easy
read() — Read Entire File
with open("sample.txt", "r") as f:
content = f.read()
print(content)
# Hello World
# Python is great
# File handling is easy
print(type(content)) # <class 'str'>
print(len(content)) # total characters including newlines
read(n) — Read n Characters
with open("sample.txt", "r") as f:
first_five = f.read(5)
print(first_five) # Hello
next_six = f.read(6)
print(next_six) # World (note the leading space)
readline() — Read One Line
with open("sample.txt", "r") as f:
line1 = f.readline()
print(line1) # Hello World\n
line2 = f.readline()
print(line2) # Python is great\n
readlines() — Read All Lines as a List
with open("sample.txt", "r") as f:
lines = f.readlines()
print(lines)
# ['Hello World\n', 'Python is great\n', 'File handling is easy\n']
# Strip newlines
clean_lines = [line.strip() for line in lines]
print(clean_lines)
# ['Hello World', 'Python is great', 'File handling is easy']
Iterating Line by Line (Best Practice)
For large files, iterate directly — this reads one line at a time and is memory-efficient:
with open("sample.txt", "r") as f:
for line in f:
print(line.strip())
# Hello World
# Python is great
# File handling is easy
This is the recommended approach for most file reading tasks.
File Encoding
Always specify encoding explicitly, especially on Windows:
# Read a UTF-8 encoded file
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# Read a file with different encoding
with open("legacy.txt", "r", encoding="latin-1") as f:
content = f.read()
Tip: Always use
encoding="utf-8"unless you know the file uses a different encoding.
File Paths
Relative Paths
# Relative to current working directory
with open("data/users.txt", "r") as f:
content = f.read()
Absolute Paths
# macOS / Linux
with open("/home/user/data/users.txt", "r") as f:
content = f.read()
# Windows (raw string to avoid escape characters)
with open(r"C:\Users\user\data\users.txt", "r") as f:
content = f.read()
pathlib — Modern File Paths
from pathlib import Path
# Cross-platform path
file_path = Path("data") / "users.txt"
# Read the file
content = file_path.read_text(encoding="utf-8")
print(content)
# Check if file exists
if file_path.exists():
print("File found!")
# Get file info
print(file_path.suffix) # .txt
print(file_path.stem) # users
print(file_path.parent) # data
print(file_path.absolute()) # /full/path/to/data/users.txt
Handling FileNotFoundError
try:
with open("nonexistent.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found! Check the path.")
Or check first:
from pathlib import Path
file_path = Path("data.txt")
if file_path.exists():
content = file_path.read_text()
else:
print("File does not exist")
Summary
| Method | Returns | Best For |
|---|---|---|
read() |
Entire file as string | Small files |
read(n) |
n characters | Peeking at file content |
readline() |
One line | Processing line by line |
readlines() |
List of all lines | When you need all lines in a list |
for line in f: |
One line per iteration | Large files (memory-efficient) |
- Always specify
encoding="utf-8"for text files - Use
pathlib.Pathfor modern, cross-platform file paths - Handle
FileNotFoundErrorfor robust code - Prefer iterating line by line for large files
Next up: Writing Files →