pathlib
Paths as objects: joining with the / operator, reading the parts of a path, and working with files.
Example
#from pathlib import Path
lesson = Path("courses") / "python" / "lesson_01.py"
print(lesson)
print(lesson.name)
print(lesson.stem, lesson.suffix)
print(lesson.parent)
print(lesson.with_suffix(".md"))The result is for Linux and macOS. On Windows, paths will be printed with backslashes, e.g. courses\python\lesson_01.py.
Definition and usage
#The pathlib module represents paths as objects of the Path class, not plain strings. You join the parts with the / operator: Path("courses") / "python". The separator is chosen automatically, so the same code works on Windows, Linux, and macOS.
A path object has attributes describing its parts: name (the full file name), stem (the name without the extension), suffix (the extension), and parent (the parent directory). Methods such as with_suffix() and with_name() create new paths without touching the disk.
The remaining methods work on files: exists(), is_file(), mkdir(), read_text(), write_text(), unlink() (deleting a file), and glob() and rglob() for finding files by pattern. In new code, pathlib is the recommended alternative to the functions in os.path.
Syntax
#from pathlib import Path
Path("directory") / "file.txt"
path.name, path.stem, path.suffix, path.parent
path.read_text(encoding="utf-8")
path.write_text(text, encoding="utf-8")
path.glob(pattern)More examples
#from pathlib import Path
notes = Path("notes.txt")
notes.write_text("The for loop\nDictionaries\n", encoding="utf-8")
print(notes.exists())
print(notes.read_text(encoding="utf-8").splitlines())
notes.unlink()
print(notes.exists())from pathlib import Path
src = Path("project") / "src"
src.mkdir(parents=True, exist_ok=True)
for name in ["main.py", "utils.py", "README.md"]:
(src / name).write_text("", encoding="utf-8")
print(sorted(path.name for path in Path("project").rglob("*.py")))The result assumes the project directory did not exist before, or contained no other .py files.
Good practices
#- With
read_text()andwrite_text(), always passencoding="utf-8", so that accented characters work the same on every system. - You can pass a
Pathobject directly toopen()and to most functions that take a path. You can turn it into a string withstr(). Path.cwd()returns the current directory, andPath.home()the userβs home directory.
Related entries
#- os vs pathlibos represents paths as plain strings and operates on them with functions, while pathlib represents a path as a Path object with methods and the / operator.
- osWorking with the operating system: paths, directories, files, and environment variables.
- open()Opens a file for reading or writing and returns a file object.
- withA context manager: automatic setup and cleanup of resources.
- jsonConverts Python data to JSON text and back. The basis for saving data and communicating with APIs.
- str.endswith()Checks whether a string ends with a given fragment.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.