Reading and Writing JSON Files
To work with files, we use the json.dump() and json.load() methods. Files must be opened in text mode ('w' or 'r').
1. Writing Python Data to a JSON File (.dump())
.dump(data, file_object) writes the Python data directly to the file stream.
python import json
user_config = {'username': 'coder1', 'email_verified': False}
with open('config.json', 'w') as f: # Use indent for pretty printing in the file json.dump(user_config, f, indent=4)
print("Configuration saved to config.json")
2. Reading JSON Data from a File (.load())
.load(file_object) reads the entire JSON file and parses it into a Python object.
python with open('config.json', 'r') as f: loaded_data = json.load(f)
print(f"Loaded username: {loaded_data['username']}") print(type(loaded_data)) # <class 'dict'>
This method is essential for storing application settings, temporary data caches, or integrating with APIs that use JSON files.