You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Python makes reading and writing files straightforward. Whether you need to read configuration files, process logs, or store program output, Python's built-in file handling has you covered.
Use the built-in open() function. Always pair it with a with statement to ensure the file is closed automatically:
with open("example.txt", "r") as file:
content = file.read()
print(content)
The second argument is the mode:
| Mode | Meaning |
|---|---|
| r | Read (default) |
| w | Write (creates or overwrites) |
| a | Append (adds to end) |
| x | Create (fails if exists) |
| b | Binary mode (combine: rb, wb) |
# Read entire file as one string
with open("data.txt", "r") as f:
content = f.read()
# Read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines() # includes newline characters
# Read line by line (memory-efficient for large files)
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes trailing newline
# Write mode — creates or overwrites the file
with open("output.txt", "w") as f:
f.write("Hello, file!\n")
f.write("Second line\n")
# Append mode — adds to existing content
with open("log.txt", "a") as f:
f.write("New log entry\n")
import os
# Check if a file exists
if os.path.exists("data.txt"):
print("File exists")
# Get the file size
size = os.path.getsize("data.txt")
print(f"Size: {size} bytes")
# Join paths safely (works on Windows and Unix)
path = os.path.join("data", "reports", "summary.txt")
For simple structured data, you can parse it manually:
# Write CSV-style data
with open("students.csv", "w") as f:
f.write("name,age,grade\n")
f.write("Alice,20,A\n")
f.write("Bob,22,B\n")
# Read and parse it
with open("students.csv", "r") as f:
header = f.readline().strip().split(",")
for line in f:
values = line.strip().split(",")
row = dict(zip(header, values))
print(row)
# {'name': 'Alice', 'age': '20', 'grade': 'A'}
try:
with open("missing.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
The with statement is the recommended pattern for all file operations — it guarantees the file is closed even if an exception occurs. This prevents file descriptor leaks in long-running programs.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.