Library contents

Python Path.parts

Compare complete path components when selecting a branch.

A simple example

Path.parts

  1. Start with Path notes/a.txt
  2. Do this Test the initial folder name
  3. Result Matches notes
Comparing path components distinguishes notes from similarly named folders.

Syntax

Python syntax
path.parts[0]
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Separate sales reports from similarly named folders

A shop imports documents from both sales and sales-old. Compare whole path components to keep the old folder out even though its spelling starts with the same letters.

Resultsales
lesson.py
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    base = Path(folder)
    for entry in (Path("sales/close.csv"), Path("sales-old/close.csv")):
        if entry.parts[0] == "sales":
            print(entry.parts[0])
Output
sales

Only the exact first component identifies the active sales folder.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. Check the last path component against the filename supplied by the catalogue. Does the complete component match?

Givenspring / alto.txt
Worked resultMatches

Locate a workshop handout

An instructor stores the current template in a class folder. Check the last path component against the filename supplied by the catalogue. Does the complete component match?

Givenceramics / glaze.pdf
Worked resultMatches

What to watch for

Lexical matches do not resolve symlinks.

Documentation for Path.parts