Practice: Files, JSON, and Paths¶
View practice code on GitHub Get the Video Course
From the lesson
Practice problems for Section 10 Concepts. Build each yourself first, then expand the solution to check.
Five practice problems, one per concept step. The numbers line up. Build each yourself, then check python-practice/solutions. Some end with a short input() "Write a Program" exercise. Each file tidies up after itself with .unlink().
These problems continue the online store story: now you are SAVING the work to disk. You write and read back the catalog, keep an orders log, save and load a product and a cart item as JSON, and inspect the path of a catalog file.
Step-01: Write a Text File, Then Read It Back¶
Concepts: with open(...), "w", "r", encoding="utf-8", .unlink().
Problem-1: Save the Catalog.
Write a program that writes the two catalog lines Wireless Mouse - 25 and Mechanical Keyboard - 45 to store_catalog.txt, reads the whole file back as one string and prints it, removes the file, then prints the done message Saved the catalog, read it back, then removed it.
Wireless Mouse - 25
Mechanical Keyboard - 45
Saved the catalog, read it back, then removed it.
Need a hint?
Open in mode "w" with encoding="utf-8", call .write() twice with \n on each line, then read it all back with one .read().
Show the solution
from pathlib import Path
with open("store_catalog.txt", "w", encoding="utf-8") as f:
f.write("Wireless Mouse - 25\n")
f.write("Mechanical Keyboard - 45\n")
with open("store_catalog.txt", "r", encoding="utf-8") as f:
catalog_text = f.read()
print(catalog_text)
Path("store_catalog.txt").unlink()
print("Saved the catalog, read it back, then removed it.")
Problem-2: Save the Store Name.
Write a program that writes the line Gadget Hub to store_name.txt (use encoding="utf-8"), reads it back, strips the whitespace, prints it as store: <text>, then removes the file.
Warning
Mode "w" always erases the whole file before writing. To add to an existing file instead of replacing it, use mode "a" (you will see this in Problem-02).
Need a hint?
Pass encoding="utf-8" on both the "w" and "r" opens, and strip() the read text before printing store: <text>.
Show the solution
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-02: Append Lines, Then Read Line by Line¶
Concepts: "a" append, read line by line, strip(), input().
Problem-1: Orders Log.
Write a program that writes order-1 to orders_log.txt, then appends order-2 and order-3 to the same file, then:
- Task-1: read the file line by line and print each line as
order: <text>(strip the newline). - Task-2: read the whole file again with
.readlines()and print how many orders there are, asorders logged: <count>.
Warning
Each write must end with \n or the lines run together on one line. Reading line by line then needs strip() to drop that trailing newline before you print.
Need a hint?
Mode "w" writes order-1 fresh, then mode "a" adds order-2/order-3; loop the file object and strip() each line, then reopen it and .readlines() gives a list, so len() is the count.
Show the solution
from pathlib import Path
with open("orders_log.txt", "w", encoding="utf-8") as f:
f.write("order-1\n")
with open("orders_log.txt", "a", encoding="utf-8") as f:
f.write("order-2\n")
f.write("order-3\n")
with open("orders_log.txt", "r", encoding="utf-8") as f:
for line in f:
print("order:", line.strip())
# Problem-1 Task-2: readlines() gives the whole file as a list, so len() counts the orders
with open("orders_log.txt", "r", encoding="utf-8") as f:
all_orders = f.readlines()
print("orders logged:", len(all_orders))
Path("orders_log.txt").unlink()
Problem-2 (Write a Program): Add an Order.
Write a program that asks the user for an order, writes Today's orders: to daily_orders.txt, appends the typed order to the same file, then reads the file back and prints it.
Need a hint?
Capture the order with input() first, write the header with "w", append the order with "a", then .read() the whole file.
Show the solution
from pathlib import Path
order = input("Enter an order: ")
with open("daily_orders.txt", "w", encoding="utf-8") as f:
f.write("Today's orders:\n")
with open("daily_orders.txt", "a", encoding="utf-8") as f:
f.write(order + "\n")
with open("daily_orders.txt", "r", encoding="utf-8") as f:
print(f.read())
Path("daily_orders.txt").unlink()
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-03: JSON - Save and Load Structured Data¶
Concepts: json.dump, json.load, json.dumps, input().
Problem-1: Save a Product.
Write a program that saves a product dict with name set to Wireless Mouse, category set to Audio, and price set to 25 to product.json, loads it back, then (after loading) removes the file. From the loaded dict:
- Task-1: print the whole loaded dict.
- Task-2: print the
namevalue asname is: <name>. - Task-3: print the
pricevalue asprice is: <price>. - Task-4: turn the loaded dict into a JSON string with
json.dumps()and print it, then print itstype()to prove it is text and not a dict.
{'name': 'Wireless Mouse', 'category': 'Audio', 'price': 25}
name is: Wireless Mouse
price is: 25
{"name": "Wireless Mouse", "category": "Audio", "price": 25}
<class 'str'>
Need a hint?
json.dump the product dict to the file, json.load it back, then index the result with ["name"] and ["price"]; json.dumps() turns that dict back into JSON text, and type() proves it is a str.
Show the solution
import json
from pathlib import Path
product = {"name": "Wireless Mouse", "category": "Audio", "price": 25}
with open("product.json", "w", encoding="utf-8") as f:
json.dump(product, f, indent=2)
with open("product.json", "r", encoding="utf-8") as f:
loaded_product = json.load(f)
# Problem-1 Task-1: print the whole loaded dict
print(loaded_product)
# Problem-1 Task-2: print the name value
print("name is:", loaded_product["name"])
# Problem-1 Task-3: print the price value
print("price is:", loaded_product["price"])
# Problem-1 Task-4: json.dumps turns the dict into a JSON string (text), not a file
text = json.dumps(loaded_product)
print(text)
print(type(text))
Path("product.json").unlink()
Problem-2 (Write a Program): Save a Cart Item.
Write a program that asks the user for a product, saves {"product": <product>} to cart.json, loads it back and prints it, then removes the file.
Need a hint?
Wrap the typed product in a dict like {"product": product} before json.dump, then json.load and print it.
Show the solution
import json
from pathlib import Path
chosen = input("Enter a product: ")
cart_item = {"product": chosen}
with open("cart.json", "w", encoding="utf-8") as f:
json.dump(cart_item, f)
with open("cart.json", "r", encoding="utf-8") as f:
print(json.load(f))
Path("cart.json").unlink()
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-04: Paths with pathlib¶
Concepts: Path joining with /, .name/.suffix/.stem/.parent, write_text()/read_text(), .exists().
Problem-1: Catalog File Path.
Write a program that builds a variable catalog_path by joining the parts catalog, app_files, and products.json into one Path with the / operator. Then, for that path:
- Task-1: print the path itself.
- Task-2: print the path's name (use
.name). - Task-3: print the path's suffix (use
.suffix). - Task-4: print the path's stem (use
.stem). - Task-5: print the path's parent (use
.parent). - Task-6: print whether the path exists (use
.exists(); this path was never created, so it isFalse).
Need a hint?
Start the chain with Path("catalog") so / joins parts; .name/.suffix/.stem/.parent read pieces and .exists() is False for an uncreated path.
Show the solution
from pathlib import Path
catalog_path = Path("catalog") / "app_files" / "products.json"
# Problem-1 Task-1: print the path itself
print(catalog_path)
# Problem-1 Task-2: print the path's name
print(catalog_path.name)
# Problem-1 Task-3: print the path's suffix
print(catalog_path.suffix)
# Problem-1 Task-4: print the path's stem
print(catalog_path.stem)
# Problem-1 Task-5: print the path's parent
print(catalog_path.parent)
# Problem-1 Task-6: print whether the path exists
print(catalog_path.exists())
Problem-2: Catalog Backup.
Write a program that builds a variable backup as a Path for catalog_backup.txt, saves the text catalog backed up to it in one step with .write_text() (end it with a newline), reads the file back in one step with .read_text(), strips the whitespace and prints it as read_text: <text>, then removes the file.
Need a hint?
.write_text() and .read_text() handle the whole file in one call each, so strip() the read result before printing read_text: <text>.
Show the solution
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-05: Save Next to Your Script¶
Concepts: __file__, Path(__file__).parent, .is_absolute(), mkdir(parents=True, exist_ok=True), rmdir().
Run this one as a file
Press F5, or run python s10_practice05_save_next_to_your_script.py. __file__ only exists while Python is running a real file, so pasting these into the terminal gives NameError.
Problem-1: Where Does It Land?
Write a program that builds a variable plain as a Path for orders.csv, and a variable beside_code that points at orders.csv next to THIS script (build it from __file__). Then:
- Task-1: print the folder of
plain(use.parent; a bare name has none, so it prints.). - Task-2: print the file name of
beside_code(use.name). - Task-3: print whether
beside_codeis pinned to one place (use.is_absolute()).
Need a hint?
Path("orders.csv") carries no folder, so its .parent prints .; build beside_code as Path(__file__).parent / "orders.csv" and .is_absolute() is then True.
Show the solution
from pathlib import Path
plain = Path("orders.csv")
beside_code = Path(__file__).parent / "orders.csv"
# Problem-1 Task-1: the folder of a bare name
print(plain.parent)
# Problem-1 Task-2: the file name of the anchored path
print(beside_code.name)
# Problem-1 Task-3: is it pinned to one place?
print(beside_code.is_absolute())
Problem-2: A Reports Folder Beside Your Code.
Write a program that builds a variable folder pointing at a demo_orders folder next to THIS script, creates it (making any missing parents, and not failing if it is already there), writes the text id,total then jan,900 on its own line into a file orders.csv inside it, then:
- Task-1: print the folder name (use
.name). - Task-2: print whether the file is really there (use
.exists()). - Task-3: remove the file, then the folder.
Need a hint?
folder.mkdir(parents=True, exist_ok=True) creates demo_orders next to the script; write_text() the rows into orders.csv, check .exists(), then .unlink() the file before folder.rmdir().
Show the solution
from pathlib import Path
folder = Path(__file__).parent / "demo_orders"
folder.mkdir(parents=True, exist_ok=True)
report = folder / "orders.csv"
report.write_text("id,total\njan,900\n", encoding="utf-8")
# Problem-2 Task-1: the folder name
print(folder.name)
# Problem-2 Task-2: is the file really there?
print(report.exists())
# Problem-2 Task-3: remove the file, then the folder
report.unlink()
folder.rmdir()
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Finished this section?
Check your work against the solutions above, then head back to the Section 10 lesson, or try the Section 10 workshop for more reps.
Prefer to learn by watching?
The full video course teaches every concept on screen and builds the projects with you, step by step.
Practice: Error Handling and Debugging Next: Practice: Standard Library Essentials