Skip to content

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.

Expected output
Engine started
Drove 50 km
Need a hint?

Mode "w" plus two .write() calls with \n, then one .read() prints both lines; clean up with .unlink().

Show the solution
s10_workshop01_sol_write_and_read_text.py
from pathlib import Path

with open("car_log.txt", "w", encoding="utf-8") as f:
    f.write("Engine started\n")
    f.write("Drove 50 km\n")
with open("car_log.txt", "r", encoding="utf-8") as f:
    print(f.read())
Path("car_log.txt").unlink()

View the full solution file on GitHub

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).

Expected output
service: Oil change
service: Tyre rotation
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
s10_workshop02_sol_append_and_read_lines.py
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()

View the full solution file on GitHub

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 brand value.
Expected output
{'brand': 'Mazda', 'year': 2020}
Mazda
Need a hint?

json.dump the car dict, json.load it back, then index ["brand"] to print Mazda.

Show the solution
s10_workshop03_sol_json_save_and_load.py
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()

View the full solution file on GitHub

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 is False).
Expected output
garage/cars/mazda.txt
mazda.txt
.txt
garage/cars
False
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
s10_workshop04_sol_paths_with_pathlib.py
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())

View the full solution file on GitHub

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_code is pinned to one place (use .is_absolute()).
Expected output
.
service.log
True
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
s10_workshop05_sol_save_next_to_your_script.py
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())

View the full solution file on GitHub

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.
Expected output
demo_garage
True
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
s10_workshop05_sol_save_next_to_your_script.py
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()

View the full solution file on GitHub

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.

Get the Video Course

Workshop: Error Handling and Debugging Next: Workshop: Standard Library Essentials

🎉 New Course
Python for Absolute Beginners
$15.99 $84.99 81% OFF
Get the Video Course