ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Python Tutorial• 6 min read

File Handling & JSON Data I/O

Context managers with open(), read vs readlines, and json serialization

Reading and writing files is fundamental for data processing. Python uses the with open(...) context manager to automatically guarantee file descriptors are safely closed.

Safe File Operations with Context Managers

Always use with open("file.txt", "r") as f:: The with statement ensures the file is closed automatically even if an exception crashes the program.

Modes: "r" (read), "w" (write/truncate), "a" (append), "r+" (read and write).

json.dump() / json.load(): Reads and writes structured Python dictionaries directly to disk as JSON files.

Reading and Writing JSON Files
import json

config_data = {
    "site_name": "Codexia Academy",
    "tracks_count": 54,
    "certified_active": True
}

# 1. Write dictionary to JSON file
with open("settings.json", "w", encoding="utf-8") as file:
    json.dump(config_data, file, indent=4)

# 2. Read JSON back into Python dictionary
with open("settings.json", "r", encoding="utf-8") as file:
    loaded_config = json.load(file)
    print("Loaded Site Name:", loaded_config["site_name"])
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Why should you always open files using the `with open(...) as f:` syntax in Python?