liveBook · Manning

Symbolic link

As explained in The Quick Python Book, Fourth Edition

A symbolic link, or symlink, is a filesystem object that refers to another filesystem path.

A symbolic link, or symlink, is a filesystem object that refers to another path. When collecting files by name, decide whether links should count before reading file sizes or moving files. section 12.6 section 12.6.2

import pathlib
cur_path = pathlib.Path("sample_data")
 
size = 0
for text_path in cur_path.rglob("*.test"):            #1
    if not text_path.is_symlink():                    #2
        size += text_path.stat().st_size              #3
        
print(size)

The recursive search finds paths ending in .test. `is_symlink()` filters them before `stat().st_size` contributes to the total. section 12.6.2

With `os` and `os.path`, apply the same rule using `os.path.islink(file_path)` before `os.path.getsize(file_path)`. The check applies to the full path assembled during directory traversal, not merely the filename. section 12.6.2

Count and move only non-links

Create a `backup` directory, then find `.test` files. For each path that is not a symlink, add its size and move it to `backup`. If the search also traverses `backup`, exclude that directory so moved files are not processed again. section 12.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates link checks within working filesystem scripts but does not explain how symbolic links are created or resolved.
Examples
Uses pathlib and os.path scripts to total non-link .test files and move eligible files into backup.
What it assumes
Assumes familiarity with Python loops and paths while showing the library calls needed to identify links.
What you can do after
Practice/perform recursive file processing that excludes symlinks before measuring or moving matching files.
How it connects
Connects symbolic links to recursive directory traversal, filename extensions, file sizes, and moving files.

Also explained in

Compare how 2 books explain symbolic link →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.