Python, properly · Chapter 17 of 42

Files with pathlib

By the end of this chapter you can name files and folders with pathlib, read and write text files safely with with and an encoding, create folders, list what is in them, and find files next to your script wherever it is run from. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Code that holds up
  • 5 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

Everything your programs have made so far vanished the moment they finished. Bhavna wants each order's kitchen ticket saved as a file the tablet in the kitchen can open; Rafiq wants a collections log that grows through the day and is still there tomorrow; and DabbaDrop's real data, 601 orders, already lives in files in /workspace/data.

A file is a named sequence of bytes on disk that outlives your program. Working with files brings new questions: where exactly is the file, which bytes stand for "₹", and what happens to a half-written file if the program crashes?

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    count_orders.py: how many orders?

    Farah wants to know how many orders September's export holds. Read /workspace/data/orders.csv with pathlib and print exactly one line:

    orders.csv has <n> orders

    where n is the number of order lines: every line of the file except the first, which is the header with the column names.

    Careful: the file ends with a newline. That does not make an extra, empty order.

  2. Task 2

    daily_log.py: append, never overwrite

    Rafiq wants a collections log that grows through the day. Write log_line(path, text): it adds text and a newline at the end of the file at path, keeping everything already there, and creates the file if it does not exist yet.

    The check calls it three times on a new file, with lines such as Collected ₹240 from D0006, and reads back exactly those three lines in order.

    Careful: the check runs your function on a computer whose default encoding is not UTF-8, so open the file with the encoding that can hold the ₹ sign.

  3. Task 3

    tickets.py: one file per order

    The kitchen tablet opens one text file per order. Write write_tickets(folder, orders): folder is a Path, orders is a dict from order id to a list of item lines, like {"D0012": ["Roti x 2", "Chole x 1"]}.

    For each order, write a file named <order id>.txt inside folder, holding the order id on the first line and then each item on its own line, every line ending with a newline. Return how many files you wrote.

    The folder, and the folders above it, may not exist yet: create them. Calling it again for the same folder must work too.

  4. Task 4

    csv_report.py: the CSV files in a folder

    Rafiq's reports folder fills up with exports. Write csv_counts(folder): for every file directly inside folder whose name ends in .csv, it returns a dict from the file's name to its number of data lines (all lines but the header).

    csv_counts on a folder holding orders.csv (header and 3 lines), empty.csv (only the header) and notes.txt returns {"orders.csv": 3, "empty.csv": 0}.

    Careful: files in folders inside folder, and files that are not .csv, are not counted.

  5. Task 5 · interview question

    Interview: specials.py, works from any folder

    specials.py prints today's specials from specials.txt, the file next to it, numbered like 1. Misal Pav. It works when you run python3 specials.py in this folder, but on the server it is run from another folder, and it stops with a FileNotFoundError.

    Fix it so it finds specials.txt next to the script, wherever it is run from, and prints the same numbered lines. The check runs it from this folder and from another one, and it reads specials.txt as it is.

    Be ready to explain why a relative path depends on where you run the program.

What you will learn

  • Paths: Path objects, joining with /, a file's name, stem, suffix and parent, relative and absolute paths.
  • Reading and writing text: read_text, write_text, and why you always pass encoding="utf-8".
  • open and with: modes r, w and a, reading line by line, and the file closed for you.
  • Folders: creating them with mkdir, listing them with iterdir and glob.

More in Code that holds up

Build "Files with pathlib" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.