Intermediate Chapter 107 · 30 min read · Module 8: File Handling
pathlib Module
- After this chapter you can create Path objects and join them with the / operator.
- You can read parts of a path such as name, stem, suffix and parent.
- You can read and write text files with read_text and write_text.
- You can create folders, list their content and search with glob and iterdir.
- You can explain when pathlib is a better choice than os.path.
In the last chapter you handled paths as plain strings and used helper functions from os.path. That works, but strings do not know anything about paths. The pathlib module, added in Python 3.4, offers a more modern idea: a path is an object with its own methods and properties.
With pathlib you can write folder / "file.txt" to join paths, ask p.suffix for the extension, and call p.read_text() to read the file. The code is shorter and easier to read than the same job done with several os functions.
In this chapter you will learn the main parts of the Path class and use them to create folders, write files and search directories. Every example is safe to run, because it only creates files in the current folder.
Creating Path objects
Import the class with from pathlib import Path. You create a path by passing text to Path(...). Path.cwd() gives the current working directory and Path.home() gives the home folder of the user. A Path object does not need to point to a real file. It is only a description of a location until you ask something about the disk.
The most loved feature is the / operator. When the left side is a Path and the right side is text, Python joins them with the correct separator for your system. You can chain it as many times as you like, for example Path("data") / "reports" / "sales.csv". This replaces os.path.join and reads almost like the path itself.
Reading the parts of a path
A Path has useful properties. name is the last part including the extension. stem is the name without the extension. suffix is the extension with its dot. parent is the path of the folder that holds it, and parts is a tuple of every piece. These properties only look at the text. They never check the disk.
from pathlib import PurePosixPath
p = PurePosixPath("data") / "reports" / "sales.tar.gz"
print(p)
print(p.name)
print(p.stem)
print(p.suffix)
print(p.suffixes)
print(p.parent)
print(p.parts)Checking, reading and writing
To ask questions about the disk use exists(), is_file() and is_dir(). To read or write small text files use read_text() and write_text(). They open the file, do the work and close it for you. There are also read_bytes() and write_bytes() for binary data. For large files that you want to process line by line, use p.open() inside a with block, just like the built-in open.
mkdir(parents=True, exist_ok=True) creates a folder and any missing parents without an error if it already exists. unlink() deletes a file and rmdir() deletes an empty folder. rename(target) renames or moves a path, and stat().st_size gives the size in bytes.
from pathlib import Path
folder = Path("notes")
folder.mkdir(parents=True, exist_ok=True)
file = folder / "todo.txt"
file.write_text("buy milk\nlearn pathlib\n")
print(file.exists(), file.is_file(), folder.is_dir())
print(file.read_text().splitlines())
print(file.stat().st_size)Searching a folder
iterdir() yields every item directly inside a folder. glob(pattern) yields items that match a pattern such as *.txt, and rglob(pattern) searches all sub-folders too. Both give you Path objects, not strings. The order is not guaranteed, so use sorted() when you print or compare results. Sorting Path objects works and sorts them by their text.
from pathlib import Path
root = Path("proj")
(root / "src").mkdir(parents=True, exist_ok=True)
(root / "a.txt").write_text("A")
(root / "b.md").write_text("B")
(root / "src" / "c.txt").write_text("C")
print([p.name for p in sorted(root.glob("*.txt"))])
print([p.name for p in sorted(root.rglob("*.txt"))])
print(sorted(p.name for p in root.iterdir()))Changing parts of a path
Paths are immutable, which means you cannot change one in place. Instead, methods return a new Path. with_suffix(".csv") swaps the extension, with_name("x.txt") swaps the whole file name, and resolve() returns the absolute path with shortcuts such as .. removed. relative_to(base) strips a leading part and returns the rest.
from pathlib import Path
old = Path("report.txt")
old.write_text("quarterly")
new = old.with_suffix(".bak")
old.rename(new)
print(old.exists(), new.exists())
print(new.name, new.read_text())pathlib or os.path?
For new code pathlib is usually the better choice. It is shorter, it avoids string mistakes and the same code runs on all systems. The os module is still useful for some jobs, and many older libraries return plain strings. Functions such as open() accept Path objects directly, and you can convert a path to text with str(p) when you must.
Python syntax
from pathlib import Path
p = Path("folder") / "file.txt"p.mkdir(parents=True, exist_ok=True)p.write_text("text")
text = p.read_text()for item in p.glob("*.txt"):
...Real-world applications
- Finding all log files in a project with rglob.
- Building output file names from input names with with_suffix.
- Writing small configuration or note files with write_text.
- Writing scripts that run on Windows, Linux and macOS without changes.
Common mistakes
Fix: At least one side of / must be a Path object, so write Path("a") / "b".
Fix: A Path is only a description. Call write_text, touch or open to create the file.
Fix: Wrap the results in sorted().
Fix: Paths are immutable. Use p.with_suffix(".csv") and keep the new path.
Important tips
- Use Path objects everywhere and convert to str only at the edge.
- Use mkdir(parents=True, exist_ok=True) for safe folder creation.
- Use stem and suffix instead of splitting strings yourself.
Key points summary
- Path objects represent locations and support the / operator.
- name, stem, suffix and parent read parts of a path.
- read_text and write_text handle small files in one call.
- glob, rglob and iterdir list folder content as Path objects.
Exam and interview points
- The / operator joins a Path and a string.
- suffix includes the dot; stem does not include the extension.
- Paths are immutable, so methods return new Path objects.
- read_text and write_text open and close the file automatically.
Quick revision
- from pathlib import Path.
- p / "x" joins paths.
- p.name, p.stem, p.suffix, p.parent.
- p.glob("*.txt") and p.rglob("*.txt") search folders.
Frequently asked questions
Is pathlib part of the standard library?
Yes. It has been included since Python 3.4, so no installation is needed.
Can I pass a Path to open()?
Yes. open() and most standard library functions accept Path objects.
What is the difference between glob and rglob?
glob searches only the given folder, while rglob also searches every sub-folder.
What is a PurePath?
A PurePath works with path text only and never touches the disk. Path adds disk operations on top of it.
Practise this chapter
20 practice questions Take the chapter quiz