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
Runs in your browser. Start straight away; create an account when you want your progress kept.
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
- Let Python close the file for you.
- Pick the second argument to open() on purpose.
- Build and take apart a path without string surgery.
- Read comma-separated data without splitting on commas.
- Save structures to a file and read them back.
- Replace a file only once the new contents are complete.
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
Previous: Errors and exceptions. Next: Classes and objects. All modules are on the course page.