File I/O and working with JSON
โ Report an issue with this lessonAlways open files with with โ it closes the file
automatically, even if an error happens partway through:
with open("notes.txt", "w") as f:
f.write("Hello, file!")
with open("notes.txt", "r") as f:
contents = f.read()
JSON is the most common structured format you'll read and write:
import json
data = {"name": "Ada", "courses": ["Python", "SQL"]}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json") as f:
loaded = json.load(f)
Try it yourself
Exercise: Given the JSON string below (like what you'd read back from data.json), use json.loads to parse it, then print the value of the 'name' key followed by the number of items in 'courses'.
Expected output:
Ada 2
Run your code and get it working before marking this lesson complete.
// that was the last free lesson
8 more lessons โ including Project: build a command-line notes tool โ plus a certificate are waiting.
Unlock the full course โ $59.99