1. Opening Files: The Basics
Python uses the built-in open() function to work with files.
file = open("example.txt", "r") # "r" = read modeCommon modes:
| Mode | Meaning |
|---|---|
"r" | Read (default) |
"w" | Write (overwrite) |
"a" | Append |
"x" | Create (error if exists) |
"b" | Binary mode (e.g. images) |
Don’t forget to close the file when done:
file.close()But a better way is to use with blocks, which auto-close the file:
with open("example.txt", "r") as file:
content = file.read()2. Reading From a File
Read the entire file:
with open("example.txt", "r") as file:
content = file.read()
print(content)Read line-by-line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes newlinesRead lines into a list:
with open("example.txt", "r") as file:
lines = file.readlines()3. Writing to a File
Overwrite mode ("w"):
with open("output.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is Python.\n")Note: "w" mode erases existing content.
Append mode ("a"):
with open("output.txt", "a") as file:
file.write("Adding another line.\n")4. Working with Paths
If your files are in different directories, use os.path or pathlib:
from pathlib import Path
file_path = Path("data") / "output.txt"
with file_path.open("w") as file:
file.write("Organized files are good files.")5. Checking If a File Exists
from pathlib import Path
file_path = Path("data.txt")
if file_path.exists():
print("File found.")
else:
print("File not found.")
6. Read & Write Structured Files (Bonus)
JSON
import json
# Write
data = {"name": "Matthew", "score": 100}
with open("data.json", "w") as file:
json.dump(data, file)
# Read
with open("data.json", "r") as file:
loaded = json.load(file)CSV
import csv
# Write
with open("scores.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["name", "score"])
writer.writerow(["Matthew", 100])
# Read
with open("scores.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)7. Common Pitfalls to Avoid
❌ Forgetting to close files (use with blocks!)
❌ Assuming a file exists (check with Path.exists())
❌ Writing in "w" mode when you meant to append
❌ Mixing binary and text modes (e.g., using "rb" vs "r")