Topic 53 of 58
File & JSON Operations
Overview
Interacting with the file system and parsing JSON (JavaScript Object Notation) are daily tasks for Python developers. JSON is the universal standard for exchanging data across the internet. Python's built-in json module provides lightning-fast serialization (converting Python dicts to JSON strings) and deserialization (converting JSON strings back into Python dicts).
Syntax
python
import json
user_data = {"name": "Alice", "age": 25, "is_active": True}
# 1. Serialization (Dict -> String)
# 'dumps' stands for Dump String
json_string = json.dumps(user_data, indent=4)
print(json_string)
# 2. Writing directly to a file
# 'dump' (without the s) writes directly to a file object
with open("export.json", "w") as file:
json.dump(user_data, file)
# 3. Deserialization (File -> Dict)
# 'load' reads directly from a file object
with open("export.json", "r") as file:
imported_data = json.load(file)
print(imported_data["name"]) # "Alice"Common Pitfalls
- Confusing
json.dump()withjson.dumps(). The 's' indicates it outputs a String. If you try to pass a file object todumps(), or a string todump(), it will crash. - Attempting to serialize custom Objects, Datetimes, or Sets directly. The
jsonstandard only supports basic primitives (dicts, lists, strings, numbers, booleans, null). You must write custom encoders to handle complex objects.
Interview Questions
Q:
If you open a file in 'w' (write) mode, what happens to the existing data in that file?
A:
The 'w' mode instantly truncates (erases) the entire file before writing. If you want to retain existing data and add to the bottom, you must use 'a' (append) mode.
Real-World Example
Reading a massive text file efficiently without destroying RAM.
example
python
with open("server_logs.txt", "r") as log_file:
# Iterating over the file object directly acts as a generator.
# It loads ONE line into memory at a time, making it capable
# of reading a 50GB file instantly.
for line in log_file:
if "ERROR 500" in line:
print(line.strip())Check Your Knowledge
Test your understanding of File & JSON Operations with these quick questions.