21. Pathlib

pathlib is the modern standard-library way to work with filesystem paths. It is usually clearer than building paths by hand with strings or older os.path helper functions.

21.1. Creating paths

Use Path objects to represent filesystem locations.

1from pathlib import Path
2
3
4root = Path('data')
5report = root / 'reports' / 'summary.txt'
6
7print(root)
8print(report)

The / operator joins path segments in a readable way.

21.2. Checking files and directories

Path objects provide convenient methods for common filesystem checks.

1from pathlib import Path
2
3
4path = Path('notes.txt')
5
6print(path.exists())
7print(path.is_file())
8print(path.suffix)

21.3. Reading and writing text

For simple tasks, Path has built-in helpers for reading and writing files.

1from pathlib import Path
2
3
4path = Path('hello.txt')
5path.write_text('Hello, world!\n', encoding='utf-8')
6
7contents = path.read_text(encoding='utf-8')
8print(contents)

21.4. Globbing

Path.glob() is useful when you want to find files matching a pattern.

1from pathlib import Path
2
3
4for path in Path('.').glob('*.py'):
5    print(path.name)

21.5. Why pathlib matters

pathlib keeps path operations object-oriented and consistent. It is easier to read than manual string concatenation, and it helps keep filesystem code portable across operating systems.

21.6. Exercise

Write a script that creates a project folder named notes with two text files inside it. Then:

  • write some text to both files

  • list all .txt files with glob()

  • print which entries are files and which are directories

  • read the contents back with Path.read_text()