Workshop: Files, JSON, and Paths (Optional, Self-Study)¶
View workshop code on GitHub Get the Video Course
From the lesson
Workshop problems for Section 10 Concepts. Build each yourself first, then expand the solution to check.
Five optional workshop problems, one per concept step, in a car scenario. Each one that creates a file tidies up with .unlink(). Self-study: check python-workshop/solutions.
Step-01: Write a Text File, Then Read It Back¶
Concepts: with open(), "w", "r", .unlink().
Write a program that writes the two log lines Engine started and Drove 50 km to car_log.txt, reads the whole file back as one string and prints it, then removes the file.
Need a hint?
Mode "w" plus two .write() calls with \n, then one .read() prints both lines; clean up with .unlink().
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().
Write a program that writes Oil change to service.txt, then appends Tyre rotation to the same file, then reads the file line by line and prints each line as service: <text> (strip the newline).
Need a hint?
Write Oil change with "w", append Tyre rotation with "a", then loop the file and strip() each line for service: <text>.
Show the solution
from pathlib import Path
with open("service.txt", "w", encoding="utf-8") as f:
f.write("Oil change\n")
with open("service.txt", "a", encoding="utf-8") as f:
f.write("Tyre rotation\n")
with open("service.txt", "r", encoding="utf-8") as f:
for line in f:
print("service:", line.strip())
Path("service.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.
Write a program that saves the dict {"brand": "Mazda", "year": 2020} to car.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
brandvalue.
Need a hint?
json.dump the car dict, json.load it back, then index ["brand"] to print Mazda.
Show the solution
import json
from pathlib import Path
car = {"brand": "Mazda", "year": 2020}
with open("car.json", "w", encoding="utf-8") as f:
json.dump(car, f)
with open("car.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
# Task-1: print the whole loaded dict
print(loaded)
# Task-2: print the brand value
print(loaded["brand"])
Path("car.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 join with /, .name/.suffix/.parent, .exists().
Write a program that builds a variable p by joining the parts garage, cars, and mazda.txt into one Path with the / operator. Then, for that path:
- Task-1: print the path itself.
Warning
The / join needs a Path on the left, so start the chain with Path("garage"). Writing "garage" / "cars" with two plain strings is an error, because you cannot divide one string by another.
- Task-2: print the path's name (use
.name). - Task-3: print the path's suffix (use
.suffix). - Task-4: print the path's parent (use
.parent). - Task-5: print whether the path exists (use
.exists(); this path was never created, so it isFalse).
Need a hint?
Begin with Path("garage") so the / operator joins the parts; .name/.suffix/.parent read pieces and .exists() is False.
Show the solution
from pathlib import Path
p = Path("garage") / "cars" / "mazda.txt"
# Task-1: print the path itself
print(p)
# Task-2: print the path's name
print(p.name)
# Task-3: print the path's suffix
print(p.suffix)
# Task-4: print the path's parent
print(p.parent)
# Task-5: print whether the path exists
print(p.exists())
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_workshop05_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 the Service Log Land?
Write a program that builds a variable plain as a Path for service.log, and a variable beside_code that points at service.log 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("service.log") carries no folder, so its .parent prints .; build beside_code as Path(__file__).parent / "service.log" and .is_absolute() is then True.
Show the solution
from pathlib import Path
plain = Path("service.log")
beside_code = Path(__file__).parent / "service.log"
# 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 Garage Records Folder Beside Your Code.
Write a program that builds a variable folder pointing at a demo_garage folder next to THIS script, creates it (making any missing parents, and not failing if it is already there), writes the text car,km then mazda,42000 on its own line into a file service.log 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) makes demo_garage beside the script; write_text() the rows into service.log, check .exists(), then .unlink() the file before folder.rmdir().
Show the solution
from pathlib import Path
folder = Path(__file__).parent / "demo_garage"
folder.mkdir(parents=True, exist_ok=True)
log = folder / "service.log"
log.write_text("car,km\nmazda,42000\n", encoding="utf-8")
# Problem-2 Task-1: the folder name
print(folder.name)
# Problem-2 Task-2: is the file really there?
print(log.exists())
# Problem-2 Task-3: remove the file, then the folder
log.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 practice 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.
Workshop: Error Handling and Debugging Next: Workshop: Standard Library Essentials