
Python
Learn best practices for file operations to write safe, efficient code.
1. Always use `with` statement
# ✅ Good - file always closes
with open("data.txt", "r") as file:
content = file.read()
# ❌ Bad - might not close if error occurs
file = open("data.txt", "r")
content = file.read()
file.close()2. Check if file exists before reading
from pathlib import Path
path = Path("config.json")
# ✅ Good - check first
if path.exists():
data = path.read_text()
else:
print("File not found!")
# ❌ Bad - error if file missing
data = path.read_text() # FileNotFoundError!3. Use proper encoding
# ✅ Good - explicit encoding
with open("text.txt", "r", encoding="utf-8") as file:
content = file.read()
# ❌ Bad - might fail on some systems
with open("text.txt", "r") as file:
content = file.read()Read Large Files Efficiently
# ❌ Bad - loads entire file into memory
with open("huge_file.txt", "r") as file:
content = file.read() # 1GB+ in memory!
# ✅ Good - process line by line
with open("huge_file.txt", "r") as file:
for line in file:
process(line) # Process one line at a timeUse Buffering for Writes
# ✅ Good - single write operation
with open("output.txt", "w") as file:
file.writelines(lines) # All at once
# ❌ Bad - many write operations
with open("output.txt", "w") as file:
for line in lines:
file.write(line) # Slow!Safe file copying
from pathlib import Path
def safe_copy(source, dest):
"""Copy file safely"""
source = Path(source)
dest = Path(dest)
if not source.exists():
raise FileNotFoundError(f"{source} not found")
with open(source, "rb") as src, open(dest, "wb") as dst:
dst.write(src.read())Safe file writing (atomic)
from pathlib import Path
import tempfile
def safe_write(path, content):
"""Write file safely (atomic)"""
path = Path(path)
# Write to temp file first
with tempfile.NamedTemporaryFile(
mode="w", dir=path.parent, delete=False
) as tmp:
tmp.write(content)
tmp_path = tmp.name
# Replace original atomically
Path(tmp_path).replace(path)Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward