Python Path.parts
Compare complete path components when selecting a branch.
A simple example
Path.parts
- Start with Path notes/a.txt
- Do this Test the initial folder name
- Result Matches notes
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.pySeparate 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
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])
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.