…
…
Python Programming Fundamentals · Lesson 35 / 40 · Files
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada wants to store the menu with its categories, not only as products and prices. Later the café's website will read the same menu. Plain text and CSV are not enough for this nested shape, so we will keep the menu in a JSON file, and today's job is clear: hot drinks go up by 20 percent, and the new prices must be saved to the file.
By the end of the lesson you will have written a function that you call as raise_prices("menu.json", "Hot drink", 20). The function returns how many products changed price. When you open and read the file again, the new prices will be there:
Output2
latte $5.10
tea $1.50
brownie $3.75
lemonade $3.25The latte went from $4.25 to $5.10 and the tea from $1.25 to $1.50. The dessert and the cold drink stayed the same. To do this, we will learn three things: what JSON is and how it maps to Python types, the four functions of the json module, and, most important, the "read, change, write back" cycle.
JSON (JavaScript Object Notation) is the standard way to store nested data structures as text and to move them between programs. The weather app on your phone usually gets its data from a server as JSON. A food-ordering app sends your basket to the server as JSON. The name comes from JavaScript, but today almost every programming language can read and write JSON. So the menu saved by Ada's Python program can be read without trouble by a website written in another language.
In lesson 34 you worked with CSV: a flat table where every row has the same columns. A menu is not flat. The café has a name, there is a list of items, and each item in the list has its own name, price, and category. In Python you build this shape as in lesson 28: "a list of dictionaries inside a dictionary". JSON is exactly the way to write this shape to a file. The data file of this lesson, menu.json, looks like this:
Output{
"cafe": "Corner Café",
"items": [
{"name": "latte", "price": 4.25, "category": "Hot drink"},
{"name": "tea", "price": 1.25, "category": "Hot drink"},
{"name": "brownie", "price": 3.75, "category": "Dessert"},
{"name": "lemonade", "price": 3.25, "category": "Cold drink"}
]
}The notation looks a lot like Python dictionaries and lists, doesn't it? On the outside there is an object in curly braces, with two keys: "cafe" and "items". The value of "items" is an array in square brackets, and each element of the array is again an object in curly braces.
In this lesson you will:
data["items"][0]["price"],When you convert JSON to Python, every part becomes a Python type. The mapping is clear and fixed:
| JSON | Python |
|---|---|
object {...} | dict |
array [...] | list |
string "..." | str |
number 85, 3.5 | int, float |
true / false | True / False |
null | None |
Look at the last two rows: in JSON, the boolean values are written in lowercase, true and false, and the empty value is null. When they move to Python, they become True, False, and None with a capital letter. Try the matching yourself:
What does each JSON part become in Python?
For each row, pick its match from the list, then check.
{...}[...]"latte"truenull3.5The rules of JSON are a little stricter than Python's, and knowing them protects you from many errors. First, strings and keys are written with double quotes; single quotes, which are fine in Python, are not valid in JSON. Second, the boolean values and the empty value are written in lowercase: true, false, null. Third, the keys of an object are always strings. Fourth, JSON has no sets or tuples: tuples become lists, and sets cannot be written at all.
The tool that does this conversion is the `json` module in Python's standard library. To use it, you write import json at the start of the program, like import csv in lesson 34. We will cover the module in detail in the next lesson; for now two functions are enough: json.dumps(data) turns a Python structure into JSON text, and json.loads(text) turns JSON text into a Python structure. Let's see both directions with an order record:
Example 1 (case): Turning an order into text and reading it back
import json order = {"table": 5, "items": ["latte", "tea"], "paid": False, "coupon": None} text = json.dumps(order) print(text) back = json.loads(text) print(back["items"][1], type(back))
Output{"table": 5, "items": ["latte", "tea"], "paid": false, "coupon": null}
tea <class 'dict'>In the first line, Python's False became false and None became null; the strings were written with double quotes. text is no longer a dictionary but an ordinary str: you can write it to a file or send it to another program. json.loads walked the road the other way and gave us a dict again; back["items"][1] read the second item, tea. Predict first:
What does this code print?
import json print(json.dumps({"tea": True, "qty": None}))
What happens to tuples and sets? A tuple quietly becomes a list; when you read it back, you have a list. A set cannot be written at all:
import json print(json.dumps({"sizes": ("S", "M")}))
Output{"sizes": ["S", "M"]}json.dumps({"latte", "tea"})Error:
OutputTypeError: Object of type set is not JSON serializableThe message says "an object of type set cannot be converted to JSON". If you need to save a set, first turn it into a list with list(...).
If you try to read a text that breaks the rules with json.loads, you get a json.JSONDecodeError. This error is a kind of ValueError, so you can catch it with the try–except ValueError pattern from lesson 32. The message usually also tells you where the problem is: Expecting property name enclosed in double quotes means "a key name in double quotes was expected", and Expecting value means "a value was expected here, but I found something I do not recognize".
One result of the rules is surprising at first: because keys are always strings, a dictionary with number keys turns its keys into strings when it is saved and read back.
import json stock = {1: "latte", 2: "tea"} back = json.loads(json.dumps(stock)) print(back) print(back.get(1), back["1"])
Output{'1': 'latte', '2': 'tea'}
None latteback.get(1) looks for the number key 1, does not find it, and returns None; the key is now the string "1". So for dictionaries you will save to JSON, using string keys from the start is the cleanest way.
Now break the rules yourself and read what Python says. The cell below runs without errors. Try three things: (1) Change true in the text to True and read the error message. (2) Add a second item to the list ({"name": "tea", "price": 1.25}) and print its name. (3) Delete the quotes around the "price" key completely: which message came?
Try it now· not graded; doesn't affect progress
Let's also clear up a common misunderstanding here: "JSON is exactly the same as a Python dictionary." It is not. When you print a Python dictionary with print, you see single quotes, True, and None; that text cannot be read as JSON. The similarity is big, but JSON is a separate notation with its own rules.
The json module has four basic functions. Two work with files, and two work with strings. An easy way to remember which is which is the s at the end: s stands for "string", that is, text.
| Function | What it does |
|---|---|
json.load(f) | Reads from an open file, returns a Python structure |
json.dump(data, f) | Writes a Python structure to an open file |
json.loads(text) | Turns JSON text into a Python structure |
json.dumps(data) | Turns a Python structure into JSON text |
The two writing functions, when given sort_keys=True, write the keys in alphabetical order. We will not use it in this lesson, but know what it does if you see it in other code.
Reading from a file starts the same way as the with open pattern from lesson 33. The only difference is that instead of reading the file line by line, you give the file object to json.load:
import json with open("menu.json", encoding="utf-8") as f: data = json.load(f)
After these two lines, data is an ordinary Python dictionary. When you work with a JSON file for the first time, you need to explore its structure step by step, because you do not know what is inside a file someone else prepared. First you check with type(data) whether the outermost structure is a dictionary or a list. If it is a dictionary, you print its keys with keys(). If it is a list, you print its length with len and its first element with [0]. Then you go down one level and repeat:
import json with open("menu.json", encoding="utf-8") as f: data = json.load(f) print(type(data)) print(data.keys()) print(len(data["items"])) print(data["items"][0].keys())
Output<class 'dict'>
dict_keys(['cafe', 'items'])
4
dict_keys(['name', 'price', 'category'])In four lines we drew the map: on the outside there is a dictionary with two keys, "items" is a list of four elements, and each item is a dictionary with the keys name, price, and category. Now writing the right chain is easy. You read the chain from left to right: data["items"] gives the list, the [1] after it gives the second element of the list, the tea dictionary, and the final ["name"] reads the name of that dictionary. Each pair of square brackets goes one level down.
Example 2 (case): Reading the menu and moving along the chain
import json with open("menu.json", encoding="utf-8") as f: data = json.load(f) print(data["cafe"]) for item in data["items"]: print(f"{item['name']}: ${item['price']:.2f}") print(data["items"][1]["name"]) print(data["items"][-1]["category"])
OutputCorner Café
latte: $4.25
tea: $1.25
brownie: $3.75
lemonade: $3.25
tea
Cold drinkHere a big advantage of JSON over CSV also shows: JSON keeps types. Every value read from CSV was a string, and you had to convert prices with float() before adding them. A 4.25 read from JSON is directly a float, and true is directly True; there is no conversion step.
On the writing side you use json.dump(data, f), and two parameters matter. `ensure_ascii=False` makes sure that letters outside the English alphabet are written as they are. If you do not give it, the json module writes every such letter with an escape sequence:
import json print(json.dumps({"name": "Corner Café"})) print(json.dumps({"name": "Corner Café"}, ensure_ascii=False))
Output{"name": "Corner Caf\u00e9"}
{"name": "Corner Café"}The first line looks broken, but the data is not broken: \u00e9 is another way of writing the letter "é", and json.load turns it back into é when it reads this file. The only problem is that a person who opens the file cannot read it. Ada also wants to check the menu by eye, so we will always write ensure_ascii=False. `indent=2` writes the JSON with two spaces of indentation at each level, one item under the other. JSON without indentation is one long line. As usual, do not forget to give encoding="utf-8" when opening the file.
Example 3 (case): Writing a readable JSON file
import json menu = {"latte": 4.25, "tea": 1.25} with open("new-menu.json", "w", encoding="utf-8") as f: json.dump(menu, f, ensure_ascii=False, indent=2) with open("new-menu.json", encoding="utf-8") as f: print(f.read())
Output{
"latte": 4.25,
"tea": 1.25
}Before changing a value in the structure you read, we need a reminder from lesson 25: two names can point to the same object. If you take a part from the middle of a chain into a variable, you get the part itself, not a copy. Follow the code below step by step and watch the boxes after each line. When the line first["price"] = 4.5 runs, does the latte dictionary inside data change too?
Run the code line by line: see which line runs next, the variable boxes and the output.
data = {"cafe": "Corner Café", "items": [
{"name": "latte", "price": 4.25},
{"name": "tea", "price": 1.25},
]}
items = data["items"]
first = items[0]
first["price"] = 4.5
print(data["items"][0]["price"])first, items[0], and data["items"][0] are three names for the same dictionary. Whatever you change through one of them shows up in the others. This is good news: when you write for item in data["items"]: in a loop and change item["price"], the change is made directly inside data. (The step-by-step view cannot open files, so we gave the data as a dictionary here; a structure read from a file behaves exactly the same.)
Now we come to the most important idea of the lesson. json.load reads the file and gives you a Python object in memory. There is no longer a link between this object and the file. When you change a price in the dictionary in memory, the file stays where it was, as if nothing had happened. For the change to last, you must open the file in "w" mode and write the whole structure again with json.dump.
Let's try it. Predict:
In menu.json the latte costs 4.25. What does this code print?
import json with open("menu.json", encoding="utf-8") as f: data = json.load(f) data["items"][0]["price"] = 4.5 with open("menu.json", encoding="utf-8") as f: print(json.load(f)["items"][0]["price"])
There are three common ways to update the structure you read, and all three are familiar from earlier lessons. To change a field: data["items"][0]["price"] = 4.5. To add a new record to the list: data["items"].append({...}). To change several records that match a condition: a loop and an if. Whichever you do, the last step is the same: write it back. In the example below we do the first two together and read the result from the file again:
Example 4 (case): Add an item, change a price, save
import json with open("menu.json", encoding="utf-8") as f: data = json.load(f) data["items"].append({"name": "water", "price": 0.75, "category": "Cold drink"}) data["items"][0]["price"] = 4.50 with open("menu.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) with open("menu.json", encoding="utf-8") as f: new = json.load(f) print(len(new["items"]), new["items"][0])
Output5 {'name': 'latte', 'price': 4.5, 'category': 'Hot drink'}This time the file really changed: when read again, it had five items and the new price of the latte. If you had opened the file in a text editor, you would have seen that each item spreads over several lines because of indent=2. In the original file each item was on one line; the look changed, the content is the same. JSON does not care about spaces and line breaks.
Remember the behavior of "w" mode from lesson 33 too: the file is emptied the moment it is opened. So you first read and prepare the structure in memory, then open with "w" and write right away. If you reverse the order, that is, open the file with "w" and then try to read, there is nothing left to read.
Before we move on to changing several records by a condition, let's look at the price calculation. A raise of rate percent means multiplying the price by (100 + rate) / 100. We round the result to two decimal places with round from lesson 3. In the code below, put different values in the rate box and see how the prices change:
How do the prices change as rate changes? What happens when you choose 0?
Pick a value; predict the output first, then look.
1rate = 02items = [{"name": "latte", "price": 4.25}, {"name": "tea", "price": 1.25}]3for item in items:4 item["price"] = round(item["price"] * (100 + rate) / 100, 2)5for item in items:6 print(item["name"], item["price"])
latte 4.25 tea 1.25
Faded lines didn't run with this value. In each turn of the loop, item is the dictionary in the list itself; item["price"] = ... changes the inside of the list directly. When rate = 0, the multiplier is 1 and the prices stay the same; at 20 they are multiplied by 1.2, and at 40 by 1.4.
Now we can write the target program. The function takes the file name, the category, and the rate. It has four steps, and we marked each step with a comment:
Example 5 (case): The target program of the lesson
import json def raise_prices(file_name, category, rate): # 1. Read with open(file_name, encoding="utf-8") as f: data = json.load(f) # 2. Update the prices of the items in the category changed = 0 for item in data["items"]: if item["category"] == category: item["price"] = round(item["price"] * (100 + rate) / 100, 2) changed += 1 # 3. Write back with open(file_name, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) # 4. How many items changed return changed print(raise_prices("menu.json", "Hot drink", 20)) with open("menu.json", encoding="utf-8") as f: for item in json.load(f)["items"]: print(item["name"], f"${item['price']:.2f}")
Output2
latte $5.10
tea $1.50
brownie $3.75
lemonade $3.25Read the function step by step. The first step brings the file into memory. The second step looks at every item; if the category matches, it updates the price and increases the counter. Because item in the loop is the dictionary in the list itself, the change goes directly into data. The third step writes the whole of data to the same file, keeping non-English letters and with indentation. The fourth step returns how many items changed; this number answers Ada's question "was the raise really applied?". If you call it with a category that does not exist, for example raise_prices("menu.json", "Coffee", 20), no if matches, the function returns 0, and the prices are written back as they were. Seeing zero makes you notice right away that you misspelled the category name.
The lines in the body of the function got mixed up. Put them in the right order; we left the counter lines out:
Put the body of the raise_prices function in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same exploring and chain logic is useful outside the café too. Imagine a response arrived from a weather service with the next days of a city. Real services answer over the internet. Python in the browser has no network, so we give the response as a ready-made text. Because the response is a string, this time we use json.loads:
Example 6 (outside the case): Reading a weather response
import json response = """{"city": "Lisbon", "days": [ {"day": "Mon", "temp": 24, "rain": false}, {"day": "Tue", "temp": 19, "rain": true}]}""" data = json.loads(response) print(data["city"]) for d in data["days"]: if d["rain"]: print(d["day"], d["temp"], "take an umbrella") else: print(d["day"], d["temp"], "sunny")
OutputLisbon
Mon 24 sunny
Tue 19 take an umbrellaNotice the line if d["rain"]:. The true in JSON arrives directly as Python's True, so there is no need for a string comparison like == "true". If you wanted to reach Tuesday's temperature directly, the chain would be data["days"][1]["temp"].
There are only a few error messages you meet when working with JSON, and each points to a specific cause. Match each message with its cause:
Which cause does each error message come from?
For each row, pick its match from the list, then check.
JSONDecodeError: Expecting property name enclosed in double quotesJSONDecodeError: Expecting value: line 1 column 10 (char 9) ({"open": True})TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapperTypeError: Object of type set is not JSON serializableJSONDecodeError: Expecting value: line 1 column 1 (char 0)You now know three ways to store your data in a file: plain text, CSV, and JSON. The choice depends on the shape of the data. For a flat table where every row has the same columns, for example hundreds of orders in a day, CSV is more compact and opens directly in spreadsheet programs. If the records contain lists or other records, for example if each product has several sizes and each size has its own price, JSON is the natural choice. It also keeps types and is the common language of websites and apps. In short: CSV for a flat table, JSON for a nested structure.
From the flat list of items we read, we build a nested dictionary that holds the item count and the price total for each category, and save it to a new file. indent=2 opens nested dictionaries level by level too.
import json with open("menu.json", encoding="utf-8") as f: data = json.load(f) summary = {} for item in data["items"]: c = item["category"] if c not in summary: summary[c] = {"count": 0, "total": 0} summary[c]["count"] += 1 summary[c]["total"] += item["price"] with open("summary.json", "w", encoding="utf-8") as f: json.dump(summary, f, ensure_ascii=False, indent=2) with open("summary.json", encoding="utf-8") as f: print(f.read())
Output{
"Hot drink": {
"count": 2,
"total": 5.5
},
"Dessert": {
"count": 1,
"total": 3.75
},
"Cold drink": {
"count": 1,
"total": 3.25
}
}Using `loads` for a file and `load` for a string. The two function names differ by only one letter, so mixing them up is very easy:
import json with open("menu.json", encoding="utf-8") as f: data = json.loads(f)
Error:
OutputTypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapperloads expects a string, but it was given an open file object (TextIOWrapper). The right way: json.load(f) when reading from a file, and json.loads(text) when you have a string in hand. The same mix-up happens when writing, and it is sneakier: if you write json.dumps(data) inside a file opened with "w", you get no error, because dumps produces the text and returns it but writes nothing to the file. The file stays empty, and the next read gives JSONDecodeError: Expecting value: line 1 column 1 (char 0). To write to a file, use json.dump(data, f, ...).
dict, array ↔ list, true/false ↔ True/False, null ↔ None. Strings and keys use double quotes, keys are always strings, and a set cannot be written.load/dump work with an open file, loads/dumps with a string. When writing, ensure_ascii=False keeps non-English letters readable, and indent=2 keeps the file readable."w" and written with json.dump. The pattern is always: read, change, write back.Next lesson: csv and json were two modules of the standard library. In the next lesson you will see import
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Many apps keep their settings in a JSON file. If the file does not exist (the app is opening for the first time), we start with default settings using the try–except from lesson 32. When a setting changes, it is written back to the file. When the function is called twice, the second call reads what the first call saved.
import json def change_setting(file_name, name, value): try: with open(file_name, encoding="utf-8") as f: settings = json.load(f) except FileNotFoundError: settings = {"theme": "light", "notifications": True} settings[name] = value with open(file_name, "w", encoding="utf-8") as f: json.dump(settings, f, ensure_ascii=False, indent=2) return settings print(change_setting("settings.json", "theme", "dark")) print(change_setting("settings.json", "notifications", False))
Output{'theme': 'dark', 'notifications': True}
{'theme': 'dark', 'notifications': False}mathrandomstatistics