Python Path equality
Compare two path values without opening the file.
A simple example
Path equality
- Start with Two paths both spelled a.txt
- Do this Compare the path values
- Result Equal
Syntax
first == second
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyDeduplicate a handout before download
A tutor receives two spellings assembled from the same folder and filename. Check their path values before creating either file so the download list has one entry per handout name.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
base = Path(folder)
first = base / "lab" / "sheet.pdf"
second = base.joinpath("lab", "sheet.pdf")
if first == second:
print("same")
same
Both constructions represent the same pathname on the current platform.
Locate a rehearsal score
The choir stores each score inside a season folder. Two labels are built with the same parent and final name. Will their normalized path values compare equal?
Locate a workshop handout
An instructor stores the current template in a class folder. Two labels are built with the same parent and final name. Will their normalized path values compare equal?
What to watch for
Path equality follows the rules of the platform. It is different from comparing file contents.