Python Path.as_uri
Represent an absolute local path as an escaped file URI.
A simple example
Path.as_uri
- Start with Unix path /tmp/a b
- Do this Convert to a file URI
- Result Space becomes %20
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.pyExport 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.
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")
escaped
The space appears as %20 in the URI.
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?
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?
What to watch for
A URI uses escaping rules that differ from local filename syntax.