Python Path.symlink_to and readlink
Create a relative symbolic link and read its stored target.
A simple example
Path.symlink_to and readlink
- Start with Link named alias points to a.txt
- Do this Read the symbolic link target
- Result a.txt
Syntax
link.symlink_to(target)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyFollow a shortcut to the latest timetable
A station maintains one current timetable and publishes a shortcut beside it. Inspect the name stored in the shortcut and verify that it still leads readers to the master timetable.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
base = Path(folder)
master = base / "master.txt"
master.write_bytes(b"09:00")
link = base / "today"
link.symlink_to(master.name)
if link.is_symlink() and link.samefile(master):
print(link.readlink())
master.txt
The relative target is resolved from the directory containing the shortcut.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. A desk makes a symbolic link named latest to the saved note. When a reader follows the link, which contents does it see?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. A desk makes a symbolic link named latest to the saved note. When a reader follows the link, which contents does it see?
What to watch for
This example requires symbolic-link support and permission to create links.