Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/File Operations Best Practices

⚙️ Performance & Best Practices — Writing Better Code

Learn best practices for file operations to write safe, efficient code.


🎯 Best Practices

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()

💡 Performance Tips

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 time

Use 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!

🎨 Common Patterns

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)

📊 Checklist

  • [ ] Always use `with` statement
  • [ ] Check file exists before reading
  • [ ] Use UTF-8 encoding explicitly
  • [ ] Process large files line-by-line
  • [ ] Batch writes for efficiency
  • [ ] Handle exceptions gracefully

🔑 Key Takeaways

  • ✅ `with` for automatic resource management
  • ✅ `Path.exists()` before reading
  • ✅ Explicit encoding (UTF-8)
  • ✅ Line-by-line for large files
  • ✅ Batch operations for performance

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn