Library contents

Python Path equality

Compare two path values without opening the file.

A simple example

Path equality

  1. Start with Two paths both spelled a.txt
  2. Do this Compare the path values
  3. Result Equal
Identically formed path values compare equal. This comparison needs no file contents.

Syntax

Python 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.py

Deduplicate 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.

Resultsame
lesson.py
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")
Output
same

Both constructions represent the same pathname on the current platform.

Advertisements

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?

Givenspring / alto.txt
Worked resultEqual

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?

Givenceramics / glaze.pdf
Worked resultEqual

What to watch for

Path equality follows the rules of the platform. It is different from comparing file contents.

Documentation for Path equality