Library contents

Python Path.absolute

Convert a relative name into an absolute pathname.

A simple example

Path.absolute

  1. Start with Current folder /work, relative file a
  2. Do this Make the path absolute
  3. Result /work/a
In this Unix-style example the current directory supplies the missing beginning of the path.

Syntax

Python syntax
receipt.absolute()
Run these examples in Python

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

python3 lesson.py

Give an attachment an absolute location

A clerk chooses a receipt by a short local name. A desktop helper working in another directory needs an absolute pathname to display the intended attachment without guessing the original working directory.

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

with TemporaryDirectory() as folder:
    base = Path(folder)
    receipt = Path("receipt.txt").absolute()
    if receipt.is_absolute() and receipt.name == "receipt.txt":
        print("absolute")
Output
absolute

The result has a root and keeps the receipt filename.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. Resolve the child name against the absolute working folder. What final filename can the desk recover from the absolute result?

Givenspring / alto.txt
Worked resultalto.txt

Locate a workshop handout

An instructor stores the current template in a class folder. Resolve the child name against the absolute working folder. What final filename can the desk recover from the absolute result?

Givenceramics / glaze.pdf
Worked resultglaze.pdf

What to watch for

An absolute pathname alone does not verify existence or resolve symbolic links.

Documentation for Path.absolute