Python Path and Path.name
Join a receipts folder and a filename, then print the filename component.
A simple example
Path and Path.name
- Start with Directory notes and name a.txt
- Do this Join the two path components
- Result notes/a.txt on Unix
Syntax
(Path("receipts") / "today.txt").name
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyBuild a receipt path without hard-coded separators
A receipt export must work on machines with different directory separators. Build the destination from its folder and filename components so each operating system can represent it correctly.
from pathlib import Path
print((Path("receipts") / "today.txt").name)
today.txt
The joined path contains a receipts directory and today.txt. Reading its final component works independently of the full path used on the computer.
Locate a rehearsal score
The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.
Locate a workshop handout
An instructor stores the current template in a class folder. Build the nested path and read its final name for the screen.
What to watch for
Use relative child names when joining paths. An absolute child can replace the parent on some platforms.