LevelJar Sign in

Python course / Working Python

Files and the filesystem

Read and write files, and handle paths, folders, CSV and JSON without string surgery. A half-written file corrupts the data it was meant to save, so you learn the write that cannot leave one.

  • with and open
  • modes
  • paths as objects
  • listing folders
  • CSV
  • JSON
  • encodings
  • safe writes

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

write it, read it back, take it apart
import json
import tempfile
from pathlib import Path

folder = Path(tempfile.mkdtemp())
prices = folder / "prices.json"

prices.write_text(json.dumps({"tea": 3.5, "jam": 2.25}), encoding="utf-8")

with prices.open(encoding="utf-8") as handle:
    loaded = json.load(handle)

print("name:", prices.name, "suffix:", prices.suffix)
print("tea costs", loaded["tea"])
name: prices.json suffix: .json
tea costs 3.5

What you will learn

The lessons in this module

  • Opening a file
  • What a forgotten close costs
  • with
  • Line by line
  • Every run starts fresh
  • Modes
  • Paths
  • Is it there, and what is it
  • Whole files in one line
  • What is in a folder
  • Making and removing
  • Text, bytes and encodings
  • CSV
  • JSON
  • Writing without losing what was there
  • Adding to a log
  • Walking a tree
  • When the filesystem says no
  • A tidy-up tool
  • Module review: the stock desk

Ready when you are

Start this module

Previous: Errors and exceptions. Next: Classes and objects. All modules are on the course page.