root@coding-prodigies:~# โ–Š
// lesson 3 of 11 ยท 16 min

File I/O and working with JSON

โš‘ Report an issue with this lesson

Always 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
python
Output

      
    

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