Python course · Module 7: Files and errors · Lesson 33 of 63
Quick answer: Python pathlib is the standard-library module for file and folder paths. Import Path, join paths with the / operator, and ask the path object for its parts and its file: Path("my_notes") / "todo.txt" gives my_notes/todo.txt, .name is "todo.txt", .exists() tells you if it is on the disk, and .read_text(encoding="utf-8") reads it. The same code works on Windows, macOS and Linux, because Path uses the right separator for each system.
In this lesson you will learn:
- how to make paths with
Path()and/, and find the current and home folders - how to get the name, stem, suffix and parent of a path
- how to create, check, list, rename and delete files and folders
- how to read and write a whole file in one line
- how Windows and Linux paths differ, and how pathlib compares with
os.path
Before you start: finish Lesson 32, Python Read and Write Files: open(), with and encoding. You also need import from Lesson 27. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, apart from the lines inside Python’s own install folder in two error messages.
Table of Contents
Python pathlib basics: Path() and the / operator
A path is the address of a file or folder, like my_notes/2026/january.txt. In older code a path is a plain string. With pathlib it is an object:
from pathlib import Path
notes = Path("my_notes")
january = notes / "2026" / "january.txt"
print(january)
print(type(january).__name__)
print(repr(january))
my_notes/2026/january.txt
PosixPath
PosixPath('my_notes/2026/january.txt')
Path("my_notes")makes a path object. The pathlib docs say that if you are not sure which class you need, “Path is most likely what you need.”- The
/operator does not divide here. The docs say it “helps create child paths, like os.path.join()”. - On Linux and macOS you get a
PosixPath; on Windows, aWindowsPathwith backslashes. Python picks the separator. - Making a path creates nothing on the disk.
The current folder and the home folder
A relative path like my_notes is looked up in the current folder, the folder you ran Python from. Two class methods give you fixed starting points:
from pathlib import Path
print("Current folder:", Path.cwd())
print("Home folder: ", Path.home())
notes = Path("my_notes")
print("Relative:", notes, notes.is_absolute())
print("Absolute:", notes.absolute(), notes.absolute().is_absolute())
print(Path.home() / "Documents" / "notes.txt")
Current folder: /home/learner/python-course/w33
Home folder: /home/learner
Relative: my_notes False
Absolute: /home/learner/python-course/w33/my_notes True
/home/learner/Documents/notes.txt
Path.cwd()is the current working folder, the same asos.getcwd().Path.home()is your user folder. Your output will show your own folders.absolute()puts the current folder in front of a relative path.is_absolute()tells you if a path already starts at the top of the disk.
name, stem, suffix and parent
A path knows its own pieces:
from pathlib import Path
january = Path("my_notes/2026/january.txt")
print("name: ", january.name)
print("stem: ", january.stem)
print("suffix:", january.suffix)
print("parent:", january.parent)
print("parts: ", january.parts)
print(list(january.parents))
backup = Path("backups/notes.tar.gz")
print(backup.suffix, backup.suffixes, backup.stem)
print(january.with_suffix(".md"))
print(january.with_name("february.txt"))
name: january.txt
stem: january
suffix: .txt
parent: my_notes/2026
parts: ('my_notes', '2026', 'january.txt')
[PosixPath('my_notes/2026'), PosixPath('my_notes'), PosixPath('.')]
.gz ['.tar', '.gz'] notes.tar
my_notes/2026/january.md
my_notes/2026/february.txt

nameis the last part: the file name with its extension.stemis the name without its last suffix, andsuffixis the extension with the dot. A file can have several suffixes:notes.tar.gzhas['.tar', '.gz'], so its stem isnotes.tar.parentis the folder that holds the file.parentswalks up one folder at a time, ending at., the current folder.with_suffix()andwith_name()return a new path with one piece changed. The old path stays the same.
All of these only read the text of the path. Python does not look at the disk, so they work even before the file exists.
Create folders with mkdir()
mkdir() creates the folder a path points to:
from pathlib import Path
year = Path("my_notes/2026")
year.mkdir(parents=True, exist_ok=True)
print(year, "is a folder:", year.is_dir())
year.mkdir(parents=True, exist_ok=True) # second time: no error
print("Second mkdir worked too")
my_notes/2026 is a folder: True
Second mkdir worked too
parents=Truealso creates missing parent folders, heremy_notesbeforemy_notes/2026.exist_ok=Truemeans “fine if the folder is already there”, so the second call does nothing.
Without these options, mkdir() is strict. A missing parent folder stops the program:
from pathlib import Path
Path("projects/2026/python").mkdir()
Traceback (most recent call last):
File "/home/learner/python-course/w33/err1_mkdir_no_parents.py", line 3, in <module>
Path("projects/2026/python").mkdir()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python3.14/pathlib/__init__.py", line 1011, in mkdir
os.mkdir(self, mode)
~~~~~~~~^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'projects/2026/python'
The second frame is inside pathlib’s own code, in Python’s install folder on our test machine, so your folder and line number will be different. Read the frame from your file and the last line. A folder that already exists gives the opposite error: Path("my_notes").mkdir() ends with FileExistsError: [Errno 17] File exists: 'my_notes'.
Read and write: write_text() and read_text()
These methods open the file, do the job and close it, in one line:
from pathlib import Path
todo = Path("my_notes") / "todo.txt"
count = todo.write_text("Buy milk\nFinish Lesson 33\n", encoding="utf-8")
print("Characters written:", count)
print(todo.read_text(encoding="utf-8"), end="")
year = Path("my_notes/2026")
(year / "january.txt").write_text("New year plans\n", encoding="utf-8")
(year / "february.txt").write_text("Exam week\nCricket match\n", encoding="utf-8")
(Path("my_notes") / "ideas.md").write_text("# Ideas\n", encoding="utf-8")
with todo.open("a", encoding="utf-8") as f:
f.write("Call Ali\n")
print(todo.read_text(encoding="utf-8").splitlines())
Characters written: 26
Buy milk
Finish Lesson 33
['Buy milk', 'Finish Lesson 33', 'Call Ali']
write_text()returns the number of characters written. Like mode"w", it replaces an old file: the docs say “An existing file of the same name is overwritten.”read_text()returns the whole file as one string.- Pass
encoding="utf-8"every time, for the same reasons as in Lesson 32. - To append or read line by line,
path.open()works likeopen()and takes the same modes.splitlines()splits the text into lines without the\n.
Check a path: exists(), is_file() and is_dir()
from pathlib import Path
for p in [Path("my_notes"), Path("my_notes/todo.txt"), Path("my_notes/done.txt")]:
print(f"{str(p):18} exists={p.exists()!s:5} is_file={p.is_file()!s:5} is_dir={p.is_dir()}")
my_notes exists=True is_file=False is_dir=True
my_notes/todo.txt exists=True is_file=True is_dir=False
my_notes/done.txt exists=False is_file=False is_dir=False
exists() is True for files and folders; is_file() and is_dir() tell them apart. A missing path gives False, not an error.
List a folder: iterdir(), glob() and rglob()
from pathlib import Path
notes = Path("my_notes")
print("iterdir():")
for item in sorted(notes.iterdir()):
kind = "folder" if item.is_dir() else "file"
print(" ", item.name, "-", kind)
print("glob('*.txt'):", sorted(p.name for p in notes.glob("*.txt")))
print("rglob('*.txt'):", sorted(str(p) for p in notes.rglob("*.txt")))
print("glob('**/*.txt'):", sorted(str(p) for p in notes.glob("**/*.txt")))
iterdir():
2026 - folder
ideas.md - file
todo.txt - file
glob('*.txt'): ['todo.txt']
rglob('*.txt'): ['my_notes/2026/february.txt', 'my_notes/2026/january.txt', 'my_notes/todo.txt']
glob('**/*.txt'): ['my_notes/2026/february.txt', 'my_notes/2026/january.txt', 'my_notes/todo.txt']
iterdir()gives everything directly inside the folder, files and folders, but not deeper.glob(".txt")gives the items in this folder that match the pattern.means “any characters”.rglob("*.txt")also searches every subfolder. The docs say it is “like calling Path.glob() with ‘**/’ added in front of the pattern”, and the last line shows the same result.- We wrap the results in
sorted()from Lesson 15. The docs sayiterdir()yields items “in arbitrary order” andglob()paths come “in no particular order”. The results also come one at a time, not as a list, so uselist()orsorted()when you need them all.
Rename and delete: rename() and unlink()
from pathlib import Path
ideas = Path("my_notes/ideas.md")
new_path = ideas.rename(ideas.with_name("ideas_old.md"))
print("Renamed to:", new_path)
print("Old name exists?", ideas.exists())
new_path.unlink()
print("Deleted?", not new_path.exists())
new_path.unlink(missing_ok=True)
print("No error with missing_ok=True")
new_path.unlink()
Renamed to: my_notes/ideas_old.md
Old name exists? False
Deleted? True
No error with missing_ok=True
Traceback (most recent call last):
File "/home/learner/python-course/w33/step8_rename_unlink.py", line 13, in <module>
new_path.unlink()
~~~~~~~~~~~~~~~^^
File "/root/.local/share/uv/python/cpython-3.14.6-linux-x86_64-gnu/lib/python3.14/pathlib/__init__.py", line 1042, in unlink
os.unlink(self)
~~~~~~~~~^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'my_notes/ideas_old.md'
rename()returns the new path. The oldideasobject still points to the old, missing name.unlink()deletes a file without asking, and there is no recycle bin.missing_ok=Trueskips the error when the file is already gone. Without it, you getFileNotFoundError.- On Windows, the docs say
rename()raisesFileExistsErrorif the target already exists, while on Linux and macOS it replaces the file silently.replace()always replaces it.
Python 3.14 also added copy() and move() to Path.
Windows paths vs POSIX paths
Windows writes C:\Users\Sara\notes.txt with backslashes and a drive letter. Linux and macOS (POSIX systems) write /home/sara/notes.txt. The pure path classes follow one system’s rules on any computer, without touching the disk:
from pathlib import Path, PurePosixPath, PureWindowsPath
win = PureWindowsPath(r"C:\Users\Sara\Documents\notes.txt")
print(win)
print("name:", win.name, "| stem:", win.stem, "| suffix:", win.suffix)
print("parent:", win.parent)
print("drive:", win.drive, "| parts:", win.parts)
print("as_posix():", win.as_posix())
print(PureWindowsPath("my_notes") / "2026" / "january.txt")
print(PurePosixPath("my_notes") / "2026" / "january.txt")
print(PureWindowsPath("C:/Users/Sara") == PureWindowsPath(r"c:\users\sara"))
print(type(Path("my_notes")).__name__)
print(Path(r"C:\Users\Sara\notes.txt").name)
C:\Users\Sara\Documents\notes.txt
name: notes.txt | stem: notes | suffix: .txt
parent: C:\Users\Sara\Documents
drive: C: | parts: ('C:\\', 'Users', 'Sara', 'Documents', 'notes.txt')
as_posix(): C:/Users/Sara/Documents/notes.txt
my_notes\2026\january.txt
my_notes/2026/january.txt
True
PosixPath
C:\Users\Sara\notes.txt
PureWindowsPathunderstands drives and backslashes even on Linux. The docs say you “cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath.”- The same
/code gives backslashes for Windows and forward slashes for POSIX. That is why you build paths with/and never type the separator yourself. - Windows paths accept forward slashes and ignore capital letters when compared, hence
True. - The last line is a warning. On Linux, a backslash is a normal character in a file name, so the whole Windows string becomes one name. The
rbefore the string is a raw string from Lesson 7.
pathlib vs os.path
Before pathlib, paths were strings handled by the os module from Lesson 27. Both ways give the same answers:
import os
from pathlib import Path
text_path = os.path.join("my_notes", "2026", "january.txt")
path = Path("my_notes") / "2026" / "january.txt"
print(text_path, "|", path)
print(os.path.basename(text_path), "|", path.name)
print(os.path.dirname(text_path), "|", path.parent)
print(os.path.splitext(text_path), "|", (path.stem, path.suffix))
print(os.path.exists(text_path), "|", path.exists())
print(open(path, encoding="utf-8").readline(), end="")
print(os.fspath(path), type(os.fspath(path)).__name__)
my_notes/2026/january.txt | my_notes/2026/january.txt
january.txt | january.txt
my_notes/2026 | my_notes/2026
('my_notes/2026/january', '.txt') | ('january', '.txt')
True | True
New year plans
my_notes/2026/january.txt str
open() accepts a Path directly, and os.fspath() or str() turns it back into a string. Here is how the common tasks match, based on the table in the pathlib docs:
| Task | os and os.path | pathlib |
|---|---|---|
| Join parts | os.path.join(a, b) | Path(a) / b |
| File name | os.path.basename(p) | p.name |
| Parent folder | os.path.dirname(p) | p.parent |
| Name and extension | os.path.splitext(p) | p.stem, p.suffix |
| Exists? | os.path.exists(p) | p.exists() |
| File or folder? | os.path.isfile(p), os.path.isdir(p) | p.is_file(), p.is_dir() |
| Current folder | os.getcwd() | Path.cwd() |
| Absolute path | os.path.abspath(p) | p.absolute() |
| Make folders | os.mkdir(p), os.makedirs(p) | p.mkdir(parents=True) |
| List a folder | os.listdir(p) | p.iterdir() |
| Rename | os.rename(a, b) | p.rename(b) |
| Delete a file | os.remove(p) | p.unlink() |
Example: a notes folder report
This script counts the lines of every text file in my_notes and its subfolders, then saves a summary in a new folder:
from pathlib import Path
notes = Path("my_notes")
total_lines = 0
for file in sorted(notes.rglob("*.txt")):
text = file.read_text(encoding="utf-8")
lines = len(text.splitlines())
total_lines += lines
print(f"{str(file.relative_to(notes)):18} {lines} lines {file.stat().st_size} bytes")
print("Total lines:", total_lines)
report = notes / "reports" / "summary.txt"
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(f"Text files: {total_lines} lines\n", encoding="utf-8")
print("Saved:", report, report.exists())
2026/february.txt 2 lines 24 bytes
2026/january.txt 1 lines 15 bytes
todo.txt 3 lines 35 bytes
Total lines: 6
Saved: my_notes/reports/summary.txt True
relative_to(notes)removes themy_notes/start, so the names are shorter.stat().st_sizeis the file size in bytes.report.parent.mkdir(parents=True, exist_ok=True)is a common pattern: make sure the folder exists, then write.
Try it yourself
Exercise 1: The parts of a path
Build the path data/2026/scores.csv with /. Print the path, then its name, stem, suffix and parent on one line.
Exercise 2: A backup folder
Create a folder backup (no error if it already exists). Write Hello from pathlib to backup/hello.txt, read it back, and check that the file is a file and the folder is a folder.
Exercise 3: Rename drafts
Make a folder drafts with intro.txt, plan.txt and photo.jpg. Then use glob() in a for loop to rename every .txt file to .md.
Solutions
Solution 1
from pathlib import Path
scores = Path("data") / "2026" / "scores.csv"
print(scores)
print(scores.name, scores.stem, scores.suffix, scores.parent)
data/2026/scores.csv
scores.csv scores .csv data/2026
The folders do not exist, and that is fine: these properties only read the path.
Solution 2
from pathlib import Path
folder = Path("backup")
folder.mkdir(exist_ok=True)
hello = folder / "hello.txt"
hello.write_text("Hello from pathlib\n", encoding="utf-8")
print(hello.read_text(encoding="utf-8"), end="")
print(hello.is_file(), folder.is_dir())
Hello from pathlib
True True
exist_ok=True lets you run the script again without FileExistsError.
Solution 3
from pathlib import Path
drafts = Path("drafts")
drafts.mkdir(exist_ok=True)
for name in ["intro.txt", "plan.txt", "photo.jpg"]:
(drafts / name).write_text("draft\n", encoding="utf-8")
for file in sorted(drafts.glob("*.txt")):
new_file = file.rename(file.with_suffix(".md"))
print(file.name, "->", new_file.name)
print(sorted(p.name for p in drafts.iterdir()))
intro.txt -> intro.md
plan.txt -> plan.md
['intro.md', 'photo.jpg', 'plan.md']
with_suffix(".md") builds the new name, and photo.jpg is untouched because it does not match *.txt.
Common mistakes
- Backslashes in a normal string.
Path("C:\Users\Sara\report.txt")fails before the program even starts:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape. Use a raw stringr"C:\Users\...", forward slashes, or build the path with/. - Adding a string with
+.Path("my_notes/todo.txt") + ".bak"givesTypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'. Usep.with_suffix(".bak")(givestodo.bak) orp.with_name(p.name + ".bak")(givestodo.txt.bak). mkdir()without options. It raisesFileNotFoundErrorwhen a parent folder is missing andFileExistsErrorwhen the folder exists. Usemkdir(parents=True, exist_ok=True).- Leaving out
encoding=.read_text()andwrite_text()follow the same encoding rules asopen(). - Expecting a sorted list from
glob(). It gives paths one by one, in no fixed order. Wrap it insorted().
Frequently asked questions
How do I check if a file exists in Python?
Make a Path and call exists(): Path("my_notes/todo.txt").exists() returns True or False. Use is_file() if it must be a file and not a folder. A missing path gives False, not an error.
How do I get the file name without the extension in Python?
Use the stem property: Path("my_notes/2026/january.txt").stem is "january". For a name with two suffixes, like notes.tar.gz, stem removes only the last one and gives notes.tar.
Should I use pathlib or os.path?
Both are in the standard library and give the same results, as our comparison showed. pathlib keeps the path and its actions in one object, so new code is shorter and easier to read. You will still meet os.path in older code, so learn to read both.
Summary
from pathlib import Path, then join parts with/:Path("my_notes") / "2026" / "january.txt".name,stem,suffixandparentread the pieces of a path without touching the disk.exists(),is_file(),is_dir(),mkdir(parents=True, exist_ok=True),iterdir(),glob(),rglob(),rename()andunlink()work with real files and folders.read_text()andwrite_text()read or write a whole file in one line; always passencoding="utf-8".PureWindowsPathshows Windows rules on any computer; build paths with/and Python picks the separator.
Next lesson
Next: Lesson 34, Python CSV and JSON Files: Read, Write and Convert.





