Library contents

Python Path.symlink_to and readlink

Create a relative symbolic link and read its stored target.

A simple example

Path.symlink_to and readlink

  1. Start with Link named alias points to a.txt
  2. Do this Read the symbolic link target
  3. Result a.txt
A symbolic link stores a target path. The target supplies the contents when the link is followed.

Syntax

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

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

Resultmaster.txt
lesson.py
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())
Output
master.txt

The relative target is resolved from the directory containing the shortcut.

Advertisements

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?

GivenFile contents “clay”
Worked resultclay

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?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

This example requires symbolic-link support and permission to create links.

Documentation for Path.symlink_to and readlink