pathlib

Paths as objects: joining with the / operator, reading the parts of a path, and working with files.

On this page

Example

#
Python
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"))
Resultsaved result, you can check it
courses/python/lesson_01.py
lesson_01.py
lesson_01 .py
courses/python
courses/python/lesson_01.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

#
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

#
Writing and reading a text file
Python
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())
Resultsaved result, you can check it
True
['The for loop', 'Dictionaries']
False
Creating directories and finding files
Python
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")))
Resultsaved result, you can check it
['main.py', 'utils.py']

The result assumes the project directory did not exist before, or contained no other .py files.

Good practices

#
  • With read_text() and write_text(), always pass encoding="utf-8", so that accented characters work the same on every system.
  • You can pass a Path object directly to open() and to most functions that take a path. You can turn it into a string with str().
  • Path.cwd() returns the current directory, and Path.home() the user’s home directory.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.