small steps

Read and write files with Python's pathlib

Save notes, read a CSV of expenses and list a folder with pathlib, the modern way to work with files in Python on any computer.

BasicsBy Noufal25 min readPublished Tested on Python 3.15
Part 4 of 4 in Python basics
6 steps in this tutorial
  1. See the problem
  2. Use Path instead of text
  3. Write and read a text file
  4. Add notes without wiping the file
  5. Read a CSV of expenses
  6. Report on every month in a folder

What you'll learn

  • Build file paths that work on Windows, macOS and Linux
  • Write, read and add to text files without losing what's there
  • Read and write CSV files, such as a list of expenses
  • Find the files in a folder by name or type

Before you start

A program forgets everything the moment it stops, unless it writes to a file. Python's pathlib gives you one tool for finding, reading and writing files that works the same on Windows, macOS and Linux. In six small steps, you'll save notes, read a CSV of your expenses and list a folder, starting with a bug that catches almost everyone on Windows once.

Step 1: See the problem

You keep notes in a folder called C:\new, and you want Python to save one there. You copy the path the way Windows shows it, and print it to check:

notes.py
path = "C:\new\notes.txt"
print(path)
C:
ew
otes.txt

Your path has turned into three lines. Inside a string, a backslash starts an escape sequence: a short code for a character you can't type directly. \n means "new line", the same code print uses to end a line. So \new became a new line followed by ew, and \notes became another new line followed by otes. Python did what you wrote, not what you meant.

Try to create the file anyway, and Windows refuses:

notes.py
path = "C:\new\notes.txt"
open(path, "w")
Output on Windows
Traceback (most recent call last):
  File "notes.py", line 2, in <module>
    open(path, "w")
    ~~~~^^^^^^^^^^^
OSError: [Errno 22] Invalid argument: 'C:\new\notes.txt'

The error shows \n inside the path, which looks right, and that's what makes this bug confusing: Python shows you the escape codes, not the new lines they stand for. macOS and Linux allow new lines in file names, so there the same code can quietly create a file with a very strange name.

Try it

In the Python shell, compare len("C:\new") with len(r"C:\new"). Why do they differ by one?

Watch out

A path with \U in it, such as "C:\Users\asha", doesn't even run. Python reads \U as the start of a Unicode code and stops with SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes. Same cause, louder error.

The usual fix is to put an r before the string, for raw, so every backslash stays a backslash (doubling them, "C:\\new\\notes.txt", does the same):

Python
path = r"C:\new\notes.txt"
print(path)
C:\new\notes.txt

That works. But the path is still plain text: you join folders and file names by hand, and a path written with backslashes only makes sense on Windows. In Step 2, Path turns it into an object that knows how paths work on every system.

Step 2: Use Path instead of text

pathlib comes with Python, so there's nothing to install. Its main tool is Path: an object that holds a path and knows how paths work on the computer it's running on. Here's where your notes will live, a notes folder in your home folder:

notes.py
from pathlib import Path

notes_dir = Path.home() / "notes"
note_file = notes_dir / "today.txt"

print(note_file.name)
print(note_file.stem, note_file.suffix)
print(note_file.parent.name)
today.txt
today .txt
notes

Three things are new here:

  • Path.home() is your home folder: C:\Users\asha on Windows, /Users/asha on a Mac, /home/asha on Linux.
  • The / sign joins parts of a path. Path gives it a new meaning, "and then, inside it", so you never type a slash or a backslash yourself, and the same line works on every system. On Windows, print(note_file) shows C:\Users\asha\notes\today.txt; on a Mac, /Users/asha/notes/today.txt.
  • .name, .stem, .suffix and .parent hand you the parts of a path, with no slicing of text.

Here's the path from Step 1, written the Path way. Forward slashes are fine in a Path, even on Windows, and print shows it the way your system writes paths:

Python
from pathlib import Path

print(Path("C:/new") / "notes.txt")
Output on Windows
C:\new\notes.txt

Try it

Make Path("report.final.csv") and print its .suffix and its .stem. Which dot does Python treat as the start of the suffix?

Watch out

Path("~/notes") isn't your home folder. In a terminal, ~ is a shortcut for home, but to Python it's an ordinary name, so this path points at a folder called ~ inside whatever folder you're in. Use Path.home() / "notes", or call .expanduser() on the path to turn the ~ into your home folder.

A Path is only a name until you create the thing it names. Make the folder now, so the next steps have somewhere to save:

notes.py
from pathlib import Path

notes_dir = Path.home() / "notes"
notes_dir.mkdir(exist_ok=True)

print(notes_dir.exists(), notes_dir.is_dir())
True True

mkdir makes the folder. exist_ok=True means "fine if it's already there", so running the script a second time doesn't stop with an error. Now you can build a path that works on any computer and make sure its folder exists. In Step 3, you'll put a file in it.

Step 3: Write and read a text file

A Path can write a whole file in one line, and read it back in another. Save two notes, then read them:

notes.py
from pathlib import Path

notes_dir = Path.home() / "notes"
notes_dir.mkdir(exist_ok=True)
note_file = notes_dir / "today.txt"

note_file.write_text("Buy milk\nCall the bank\n", encoding="utf-8")

text = note_file.read_text(encoding="utf-8")
print(text.splitlines())
['Buy milk', 'Call the bank']

write_text creates the file if it isn't there and saves the text you give it. Each \n ends a line, as in Step 1, but this time on purpose. read_text gives you the whole file back as one string, and splitlines() cuts it into a list with one item per line.

encoding="utf-8" tells Python how to turn your text into bytes on the disk. UTF-8 can store every language, from English to Malayalam to emoji, and it's what almost every other program expects. Pass it on every read and write.

Watch out

Leave out encoding on Windows with Python 3.14 or older, and Python saves with the old Windows code page instead of UTF-8. A note in Malayalam, such as "ചെറിയ ചുവടുകൾ", then stops with UnicodeEncodeError: 'charmap' codec can't encode characters. Python 3.15 made UTF-8 the default everywhere (PEP 686 (opens in a new tab)), but your code may still run on an older Python. encoding="utf-8" costs nothing and works on every version.

Try it

Change today.txt to tomorrow.txt in the line that reads the file, but not in the line that writes it, and run it again. What does Python tell you? Which method from Step 2 could check first?

Now add a third note the same way:

Python
note_file.write_text("Pay rent\n", encoding="utf-8")
print(note_file.read_text(encoding="utf-8").splitlines())
['Pay rent']

Your first two notes are gone. write_text replaces everything in the file, every time. That's right for a file you rebuild from scratch, and wrong for a notes file. In Step 4, you'll add to a file without wiping it.

Step 4: Add notes without wiping the file

To add to the end of a file, open it in append mode. Here's a small notes saver: run it, type a note, and it's saved with today's date under the notes you already have:

note.py
from datetime import date
from pathlib import Path

notes_dir = Path.home() / "notes"
notes_dir.mkdir(exist_ok=True)
note_file = notes_dir / "notes.txt"

note = input("Note: ")
with note_file.open("a", encoding="utf-8") as f:
    f.write(f"{date.today()}  {note}\n")

print(note_file.read_text(encoding="utf-8"), end="")

Run it twice (type python3 instead of python on macOS and Linux):

Terminal
$ python note.py
Note: Buy milk
2026-12-01  Buy milk
$ python note.py
Note: Call the bank
2026-12-01  Buy milk
2026-12-01  Call the bank

Your dates will be different, but the second note is added under the first. Here's what each new part does:

  • note_file.open("a", ...) opens the file for appending: new text goes at the end, and anything already there stays. The other modes you'll meet are "w", which wipes the file first, as write_text does, and "r", for reading, which is what you get if you leave the mode out.
  • with ... as f: keeps the file open while the indented block runs and closes it when the block ends, even if something inside goes wrong. Closing matters: until a file is closed, some of what you wrote can still be waiting in memory.
  • f.write(...) adds your text. date.today() inside an f-string prints the date as year-month-day, so the notes sort in date order.
  • end="" stops print from adding a line break of its own, because the file already ends with one.

Watch out

write doesn't end the line for you, the way print does. Leave out the \n, and every note lands on the same line: 2026-12-01 Buy milk2026-12-01 Call the bank.

Try it

Run note.py once more and press Enter without typing anything. What gets saved? Add an if so that an empty note isn't saved.

Now you can keep a file growing, one line at a time. Notes are free text, though. In Step 5, you'll read a file with columns, a list of expenses, and add it up.

Step 5: Read a CSV of expenses

A CSV file (comma-separated values) is a table saved as text: the first line names the columns, and each line after it is one row. Banks and spreadsheet apps can export one. Here's a month of expenses in whole rupees. This script saves it in an expenses folder, so you have one to work with:

make_expenses.py
from pathlib import Path

expenses_dir = Path.home() / "expenses"
expenses_dir.mkdir(exist_ok=True)

month_file = expenses_dir / "2026-11.csv"
month_file.write_text(
    "date,category,item,amount\n"
    "2026-11-02,food,Vegetables,240\n"
    "2026-11-03,travel,Auto to station,90\n"
    "2026-11-05,bills,Electricity,1150\n"
    "2026-11-09,food,Groceries,860\n"
    "2026-11-14,travel,Bus pass,500\n",
    encoding="utf-8",
)
print(month_file.name, "saved")
2026-11.csv saved

Python joins strings written next to each other into one, so each line of the file gets its own line of code. The file is named after its month, year first, for a reason you'll see in Step 6.

Now read it back and add up what you spent in each category:

expenses.py
import csv
from pathlib import Path

month_file = Path.home() / "expenses" / "2026-11.csv"

totals = {}
with month_file.open(encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f):
        category = row["category"]
        amount = int(row["amount"])
        totals[category] = totals.get(category, 0) + amount

for category in sorted(totals):
    print(f"{category:<8}{totals[category]:>6}")
print(f"{'total':<8}{sum(totals.values()):>6}")
bills     1150
food      1100
travel     590
total     2840

Here's how it works:

  • csv comes with Python. csv.DictReader reads the first line as the column names and hands you every row after it as a dictionary. The first row is {'date': '2026-11-02', 'category': 'food', 'item': 'Vegetables', 'amount': '240'}, so row["category"] is 'food'.
  • newline="" is what the csv documentation (opens in a new tab) asks for whenever you open a CSV file: it lets the csv module deal with line endings itself. It matters most when you write one, which you'll do in Step 6.
  • totals.get(category, 0) is the total so far for that category, or 0 the first time it turns up.
  • sorted(totals) gives the category names in alphabetical order, and the widths in the f-strings, :<8 and :>6, line up the columns, as in the f-strings tutorial.

Watch out

Everything a CSV file gives you is text, even 240. Leave out int(...), and adding the first amount stops with TypeError: unsupported operand type(s) for +: 'int' and 'str'. Turn each value into the type you need as you read it.

Try it

Add a line to 2026-11.csv for a new category, such as 2026-11-20,health,Medicines,320, and run expenses.py again. Where does health appear in the list, and what's the new total?

Now you can read a table from a file and add it up. In Step 6, you'll find every month's file in the folder and write one report for all of them.

Step 6: Report on every month in a folder

One month is a start. Add last month too, so the folder has two files to find:

make_october.py
from pathlib import Path

(Path.home() / "expenses" / "2026-10.csv").write_text(
    "date,category,item,amount\n"
    "2026-10-03,food,Vegetables,310\n"
    "2026-10-05,bills,Electricity,1150\n"
    "2026-10-08,travel,Auto to market,160\n"
    "2026-10-15,food,Groceries,670\n"
    "2026-10-21,travel,Train ticket,250\n",
    encoding="utf-8",
)
print("2026-10.csv saved")
2026-10.csv saved

glob finds the files in a folder whose names match a pattern. In "*.csv", the * stands for any name, so the pattern means "every file ending in .csv":

months.py
from pathlib import Path

expenses_dir = Path.home() / "expenses"

for path in sorted(expenses_dir.glob("*.csv")):
    print(path.stem, path.suffix)
2026-10 .csv
2026-11 .csv

Here's the reason the files are named year first: sorted as text, 2026-10 comes before 2026-11, so the months come out in date order. Names like november.csv and october.csv would sort alphabetically, November first. (iterdir() gives you everything in a folder, whatever its name, if you ever need that.)

Watch out

glob doesn't promise any order: on another computer, the same files can come back in a different one. Wrap it in sorted(...) whenever order matters, as it does in a report.

Now the small program the whole tutorial has been building to. It reads every month's file, totals each one by category, saves a summary with one row per month, and prints it:

report.py
import csv
from pathlib import Path

expenses_dir = Path.home() / "expenses"
reports_dir = expenses_dir / "reports"
reports_dir.mkdir(parents=True, exist_ok=True)

months = {}
for path in sorted(expenses_dir.glob("*.csv")):
    totals = {}
    with path.open(encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            category = row["category"]
            amount = int(row["amount"])
            totals[category] = totals.get(category, 0) + amount
    months[path.stem] = totals

categories = set()
for totals in months.values():
    categories.update(totals)
categories = sorted(categories)

rows = [["month"] + categories + ["total"]]
for month, totals in months.items():
    amounts = [totals.get(category, 0) for category in categories]
    rows.append([month] + amounts + [sum(amounts)])

summary = reports_dir / "summary.csv"
with summary.open("w", encoding="utf-8", newline="") as f:
    csv.writer(f).writerows(rows)

for row in rows:
    line = f"{row[0]:<9}"
    for cell in row[1:]:
        line += f"{cell:>7}"
    print(line)
month      bills   food travel  total
2026-10     1150    980    410   2540
2026-11     1150   1100    590   2840

Open summary.csv in a spreadsheet, and the months sit side by side. Here's what's new:

  • mkdir(parents=True, exist_ok=True) makes reports and any missing folder above it, and does nothing if they're all there.
  • The first loop is Step 5's, once per file. path.stem, such as 2026-10, becomes the month's name in months.
  • A set keeps each value only once, so categories ends up with every category any month used, even one that appears in a single month. sorted turns it into a list in alphabetical order.
  • totals.get(category, 0) for category in categories builds one amount per category, with 0 for a category the month didn't use, so every row has the same columns.
  • csv.writer(f).writerows(rows) writes every row, putting the commas in for you, and quotes any value that has a comma in it.
  • glob("*.csv") only looks in expenses itself, not inside reports, so the report never reads its own summary.csv as a month.

Watch out

On Windows, leave out newline="" when you write a CSV, and every row ends with an extra hidden character. Many programs then show an empty row after each real one, and reading the file back with csv gives you empty rows too.

Try it

Add a 2026-12.csv with a new category, such as 2026-12-05,shopping,Shoes,1800, and run report.py again. Which months get 0 in the new shopping column?

Now you can find files by name, read each one and write one report for them all: the same steps work for a year of bank statements or a folder of exam marks.

Recap

  • Build paths with Path and /, never by gluing text together. Path.home() and / work the same on Windows, macOS and Linux.
  • write_text and read_text save and load a whole file. Pass encoding="utf-8" every time.
  • To add to a file without wiping it, open it in "a" mode inside with, and end each line with \n yourself.
  • csv.DictReader and csv.writer read and write tables. Open CSV files with newline="", and turn text into numbers with int().
  • glob("*.csv") finds files by pattern. Sort what it finds, and name files so they sort the way you want.

Check yourself

Five quick questions.

print("C:\new\notes.txt") prints the path on three lines. Why?
Show the answer

Inside a string, \n means a new line: Each \n is one character, a line break. Write r"C:\new\notes.txt", or better, build the path with Path.

Where does Path("~/notes") point?
Show the answer

At a folder called ~, inside the folder you run the script from: To Python, ~ is an ordinary name. Use Path.home() / "notes", or call .expanduser() on the path.

You call note_file.write_text("Buy milk\n", encoding="utf-8"), then the same with "Pay rent\n". What is in the file?
Show the answer

Only Pay rent: write_text replaces the whole file every time. To add a line, open the file in "a" mode, as in Step 4.

totals.get(category, 0) + row["amount"] stops with a TypeError. Why?
Show the answer

Every value a CSV file gives you is text, so this is 0 + "240": The csv module hands you strings, even for numbers. Turn the amount into a number first: int(row["amount"]).

Your files are october.csv, november.csv and december.csv. In what order does sorted(folder.glob("*.csv")) give them?
Show the answer

December, November, October: sorted compares names as text, letter by letter. Name the files 2026-10.csv and so on, and text order is date order.