liveBook · Manning

Pathlib

As explained in The Quick Python Book, Fourth Edition

pathlib is a Python standard-library module that provides object-oriented classes and operations for representing and manipulating filesystem paths.

`pathlib` represents filesystem locations as `Path` objects. It provides an object-oriented alternative to `os` and `os.path` for building paths, inspecting files and directories, and performing filesystem operations. Available since Python 3.5, it often makes the same tasks more concise. section 12.1

Build and inspect a path

Use `from pathlib import Path` and `path = Path('some', 'directory', 'path.jpg')`. Then `path.name` is `'path.jpg'`, `path.parent` is `Path('some/directory')`, and `path.suffix` is `'.jpg'`. `path.parts` gives the components as a tuple. Build further paths with `path.joinpath(...)` or the `/` operator; the resulting path follows the operating system’s path conventions. section 12.2.5

Common operations stay attached to the path they act on:

  • `Path.cwd()` gets the current directory. Creating another `Path` lets you work with a different location, but does not change the process’s current directory. section 12.2.3
  • `iterdir()` yields paths in a directory; `glob(pattern)` yields matching paths. Use `rglob(pattern)` to search subdirectories. section 12.4.1 section 12.6.2
  • `rename(new_path)` can move a file to another directory. `mkdir(parents=True)` creates needed intermediate directories, while `mkdir(exist_ok=True)` accepts an existing directory. section 12.4.1 section 12.6.2
  • `unlink()` deletes a file, not a directory; `rmdir()` removes only an empty directory. section 12.4.1

Total matching file sizes

Starting with `root = Path('sample_data')`, loop over `root.rglob('*.test')`. For each path that is not a symlink (`not path.is_symlink()`), add `path.stat().st_size` to a running total. The search, symlink check and size lookup all use methods on path objects. section 12.6.2

Listing 20.1 File files_01.py
import datetime
import pathlib
 
FILE_PATTERN = "*.txt"                                        #1
ARCHIVE = "archive"
 
def main():
    
    date_string = datetime.date.today().strftime("%Y-%m-%d")  #2
 
    cur_path = pathlib.Path(".")
    archive_path = cur_path.joinpath(ARCHIVE)       
    archive_path.mkdir(exist_ok=True)                         #3
 
    paths = cur_path.glob(FILE_PATTERN)
 
    for path in paths:
        new_filename = f"{path.stem}_{date_string}{path.suffix}"
        new_path = archive_path.joinpath(
                                         new_filename)        #4
        path.rename(new_path)                                 #5
 
if __name__ == '__main__':
     main()

A complete archiving script finds matching text files, creates an archive directory, adds a date to each filename using `stem` and `suffix`, then moves each file with `rename()`. section 20.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through path properties and filesystem methods, then combines them in scripts; defers the full method catalog to the documentation.
Examples
Demonstrates path components, recursive .test file-size totals, and a dated archive for matching text files.
What it assumes
Assumes familiarity with Python imports and basic files and directories; introduces Path construction through short examples.
What you can do after
Build it from scratch: search for matching files, inspect them, and move them into a created directory with pathlib.
How it connects
Connects Path methods to os and os.path alternatives, glob patterns, symbolic links, and file input and output.

Also explained in

Compare how 2 books explain pathlib →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.