python start lecture 13
python start lecture 13
Mode Meaning
"r" Read (default), error if file doesn’t exist
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
0
2
JSON in Python
What is JSON?
📊 JSON (JavaScript Object Notation) = A lightweight
data format for storing structured data.
💡 Looks like a Python dictionary:
{
"name": "Alice",
"age": 25,
"city": "New York"
}
🔹 Used in APIs, config files, databases.
Converting Python Data to JSON
Python dictionary → JSON string:
import json
data = {"name": "Abobus", "age": 25}
json_string = json.dumps(data, indent = 4) # Pretty-printing
print(json_string)
loaded_data = json.load(file)
print(loaded_data["name"]) # Abobus