Reading & writing files with pathlib
Read, process and write text files safely with context managers.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
pathlib.Path represents file paths as objects that work on every OS. Opening files inside a with-block guarantees they are closed, even if an error happens while reading or writing.
Explained simply
Until now your programs forgot everything when they stopped. Files let a program keep data: notes, logs, settings, results. Reading a file brings text into your program; writing a file saves text for later or for another program.
A path is the address of a file, like data/notes.txt. Windows writes paths with backslashes and macOS and Linux with forward slashes. The pathlib module hides that difference. You build a Path object, and Python writes the right kind of path for whatever computer runs the code.
Opening a file is like borrowing a book: you must give it back. If you forget to close a file, your changes may not be saved yet, and on some systems other programs cannot use it. The with-block closes the file for you as soon as the block ends, even if your code crashes.
Text in a file is stored as bytes. An encoding is the rule that turns bytes into letters. UTF-8 handles every language and emoji, so always say encoding="utf-8". If you skip it, Python uses your computer's default, and the same script may break on a colleague's machine.
Press Play on a diagram to walk through it one step at a time.
- 1Build a Path
Path("data") / "notes.txt" joins parts safely
- 2Open in with-block
Mode "r" read, "w" overwrite, "a" append
- 3Read line by line
for line in f keeps memory use low
- 4Process & write
Write results to another file
- 5Auto close
Leaving the with-block closes the file
- parent
- /home/ana/data
- name
- sales.csv
- stem
- sales
- suffix
- .csv
- parts
- ('/', 'home', 'ana', 'data', 'sales.csv')
In depth
Path objects: the parts you will use every day
A Path is not the file itself; it is just the address. Creating Path("report.txt") does not touch the disk. Methods like exists(), is_file() and read_text() actually look at the disk.
Useful attributes for p = Path("data/2026/sales.csv"): p.name is sales.csv, p.stem is sales, p.suffix is .csv, and p.parent is data/2026. p.with_suffix(".json") gives a new path with a different extension. Join parts with the / operator: Path("data") / "2026" / "sales.csv".
Relative paths are relative to the current working directory, which is wherever you ran python from, not where your script lives. That is a classic bug: the script works from one folder and fails from another. To find files next to your script, use Path(__file__).resolve().parent as the base. Path.home() gives the user's home folder, and Path.cwd() the current working directory.
- mkdir(parents=True, exist_ok=True) creates nested folders safely
- unlink(missing_ok=True) deletes a file without failing if it is gone
- resolve() turns a relative path into a full absolute one
File modes and what really happens when you write
open() takes a mode. "r" reads (the default) and fails with FileNotFoundError if the file is missing. "w" creates the file or empties an existing one immediately, before you write anything. "a" appends to the end. "x" creates a new file and raises FileExistsError if it already exists, which is a safe way to avoid overwriting. Add "b" for binary data like images ("rb", "wb"), where you get bytes instead of str.
Writes are buffered: Python collects text in memory and sends it to the disk in chunks. The data is only guaranteed to be handed to the OS when the buffer is flushed, which happens when the file is closed. If the program crashes before that, the last writes can be lost.
In text mode, Python also translates line endings. Reading turns Windows \r\n into \n. Writing turns \n into the system's line ending. Binary mode never changes bytes.
- File must exist
- Starts at the beginning
- Default mode
- FileNotFoundError if missing
- Creates or empties the file
- Erases old content at once
- Use for fresh output
- "x" instead to refuse overwriting
- Creates if missing
- Always writes at the end
- Keeps old content
- Ideal for logs
Reading big files without running out of memory
read_text() and f.read() load the whole file into one string. That is fine for a config file, but a 5 GB log would need 5 GB of memory. Iterating over the file object instead (for line in f) reads one line at a time, so memory stays small no matter how big the file is.
Each line keeps its newline at the end, so use line.rstrip("\n") or line.strip() before comparing. f.readlines() looks handy but also loads everything into a list. For binary files, read in fixed-size chunks with f.read(65536) in a loop.
To count lines, find matches or build totals, streaming line by line is the normal pattern. You can also stream into another file at the same time, as in the explainer's example, so the whole job runs in constant memory.
- sum(1 for _ in f) counts lines without storing them
- enumerate(f, start=1) gives line numbers for error messages
- Use errors="replace" to read files with a few broken bytes
Saving safely: write to a temp file, then replace
If your program crashes or the power fails while writing data.json with mode "w", you can be left with a half-written file, and the old data is already gone. For important files, use a two-step pattern. First write the new content to a temporary file in the same folder, such as data.json.tmp. Then call Path.replace() to swap it into place.
On the same filesystem, replace is atomic: anyone reading the file sees either the complete old version or the complete new one, never a mix. It also overwrites the target on both Windows and Unix, unlike rename, which fails on Windows if the target exists.
This matters for your capstone too: an expense tracker that corrupts its own JSON file on a crash loses the user's data.
- 1Build new content
json.dumps(items, indent=2)
- 2Write data.json.tmp
Same folder as the real file
- 3Close the temp file
Buffers flushed to the OS
- 4tmp.replace(target)
Atomic swap on the same disk
- 5Old or new, never half
Readers always see a whole file
Listing and filtering files in a folder
folder.iterdir() yields every entry directly inside a folder, files and subfolders, in no guaranteed order, so wrap it in sorted() if order matters. folder.glob("*.txt") matches names with a pattern: * matches any characters, ? matches one character, and [0-9] matches one digit. folder.rglob("*.txt") searches all subfolders too.
Glob patterns only look at names. To filter by other things, combine with a condition: p.is_file(), p.stat().st_size for size in bytes, or p.stat().st_mtime for the last-modified time as a timestamp. Hidden files that start with a dot are matched by * in pathlib, unlike in many shells.
For very large trees, os.scandir is faster because it reads file types along with names. Python 3.12 also added Path.walk(), which works like os.walk and returns each folder with its subfolders and files.
- sorted(Path("logs").glob("*.log")) gives a stable order
- max(files, key=lambda p: p.stat().st_mtime) finds the newest file
- datetime.fromtimestamp(p.stat().st_mtime) shows a readable date
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Build paths with pathlib.Path~35m
- 2Read text files with a with-block~35m
- 3Write and append to files~35m
- 4Process a file line by line~35m
- 5List and filter files in a folder~35m
Key points
- Use the / operator to join paths instead of gluing strings with slashes.
- Always pass encoding="utf-8" when reading or writing text.
- Mode "w" erases the file first; use "a" to add to the end.
- path.read_text() is fine for small files; loop over lines for big ones.
- folder.glob("*.csv") lists matching files in a folder.
Key terms
Tap a card to flip it. 0/5 known
Examples
from pathlib import Path
src = Path("data") / "log.txt"
out = Path("data") / "errors.txt"
with src.open(encoding="utf-8") as f, out.open("w", encoding="utf-8") as w:
for line in f:
if "ERROR" in line:
w.write(line)
for p in Path("data").glob("*.txt"):
print(p.name, p.stat().st_size, "bytes")A script that works from any folder
Your script reads settings.txt from the same folder. It works when you run python app.py inside the folder, but fails with FileNotFoundError when run from the parent folder as python tools/app.py. Step 1: realise that "settings.txt" is relative to the current working directory, not to the script. Step 2: build a base path from __file__. Step 3: join the file name onto it. Now the script finds its file wherever you run it from.
from pathlib import Path
BASE = Path(__file__).resolve().parent
settings = BASE / "settings.txt"
print("cwd: ", Path.cwd())
print("script:", BASE)
for line in settings.read_text(encoding="utf-8").splitlines():
key, _, value = line.partition("=")
print(key.strip(), "->", value.strip())Saving a to-do list without risking corruption
A small to-do app saves its list to todo.txt every time you add an item. Step 1: build the new text in memory. Step 2: write it to todo.txt.tmp with the same encoding. Step 3: replace the real file in one atomic step. Step 4: on start, if todo.txt does not exist yet, begin with an empty list instead of crashing. A crash at any moment leaves either the old list or the new one.
from pathlib import Path
TODO = Path("todo.txt")
def load() -> list[str]:
if not TODO.exists():
return []
return TODO.read_text(encoding="utf-8").splitlines()
def save(items: list[str]) -> None:
tmp = TODO.with_suffix(".txt.tmp")
tmp.write_text("\n".join(items) + "\n", encoding="utf-8")
tmp.replace(TODO)
items = load()
items.append("buy milk")
save(items)Quick reference
- Path(__file__).resolve().parent is the folder of the running script
- p.name, p.stem, p.suffix, p.parent split a path into parts
- Mode "x" creates a new file and raises FileExistsError instead of overwriting
- for line in f streams a file line by line in constant memory
- Write to a .tmp file, then tmp.replace(target) for an atomic save
- folder.rglob("*.py") searches all subfolders
- p.stat().st_size is the size in bytes; st_mtime is the last-modified time
Common mistakes
- Opening with "w" by accident and wiping the existing file.
- Relying on the current working directory; build paths from a known base.
- Forgetting each line keeps its trailing newline; use line.rstrip().
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a script that asks for a line of text and appends it, with the current date, to journal.txt. Run it three times and print the file.
- Exercise 2medium
Print the five largest files under a folder (including subfolders), with their sizes in KB, largest first.
- Exercise 3hard
Read a large app.log line by line and write every line containing ERROR to errors.txt, prefixed with its line number. Print how many errors were found. Use constant memory.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use pathlib or os.path?
- Use pathlib in new code. It is part of the standard library, works on every OS and is easier to read; os.path still works and you will see it in older code.
- Why do I get UnicodeDecodeError when reading a file?
- The file's bytes do not match the encoding Python used, often because no encoding was given. Pass encoding="utf-8", or the file's real encoding if you know it, and use errors="replace" only if a few bad characters are acceptable.
- Do I need to call close() if I use with?
- No. The with-block closes the file automatically when it ends, even if an exception happens inside it.
- How do I delete a folder with files in it?
- Path.rmdir() only removes empty folders. Use shutil.rmtree(path) for a folder with contents, carefully, because it deletes everything inside without asking.