Library contents

Python Path.as_uri

Represent an absolute local path as an escaped file URI.

A simple example

Path.as_uri

  1. Start with Unix path /tmp/a b
  2. Do this Convert to a file URI
  3. Result Space becomes %20
A URI encodes the space while retaining the underlying filename.

Syntax

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

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

python3 lesson.py

Export a receipt as a local file URI

A stationery shop wants to open a locally saved receipt in a desktop viewer. Convert its filename to a file URI so the space in the name travels correctly through the viewer’s URL interface.

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

with TemporaryDirectory() as folder:
    base = Path(folder)
    receipt = base / "May sales.txt"
    if receipt.as_uri().endswith("May%20sales.txt"):
        print("escaped")
Output
escaped

The space appears as %20 in the URI.

Advertisements

Share a score location

A music librarian exports a local link to a score with a space in its name. Turn the local path into a file URI. How is the space in the final filename represented?

GivenChoir A.pdf
Worked resultChoir%20A.pdf

Link a work order

A carpenter sends the location of a workshop document to another desktop tool. Turn the local path into a file URI. How is the space in the final filename represented?

GivenBench 2.txt
Worked resultBench%202.txt

What to watch for

A URI uses escaping rules that differ from local filename syntax.

Documentation for Path.as_uri