liveBook · Manning

Os.path.islink

As explained in The Quick Python Book, Fourth Edition

os.path.islink is a Python os.path function that returns whether a path identifies a symbolic link.

os.path.islink(path) returns True when path identifies a symbolic link and False otherwise. It is useful when filesystem code must distinguish links from ordinary files before inspecting or moving them. section 12.3

Keep these platform and usage details in mind:

  • Use it alongside os.walk, os.path.splitext, and os.path.getsize to exclude links while scanning files, such as .test files. section 12.6.2
  • On Linux and other UNIX systems, it tests file links; on Windows, it recognizes true symbolic links created with mklink(), but not .lnk shortcut files. section 12.3
  • The pathlib alternative is Path.is_symlink(), which provides similar functionality when paths are represented as Path objects. section 12.3 section 12.6.2

Skip symbolic links during a recursive scan

import os size = 0 for root, _, files in os.walk('.'): for name in files: path = os.path.join(root, name) if not os.path.islink(path) and name.endswith('.test'): size += os.path.getsize(path) print(size) 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)

Compare the pathlib form of the same file-scan pattern, using Path.is_symlink() before reading file sizes. section 12.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the boolean query and platform distinction but does not descend into link-resolution internals.
Examples
Uses recursive .test-file scans that calculate sizes or move matching non-symlinks into a backup directory.
What it assumes
Assumes familiarity with paths, files, directories, and basic os module operations.
What you can do after
Apply it via os.walk to avoid counting or moving symbolic links during recursive file operations.
How it connects
Connects with os.walk, os.path.getsize, os.path.splitext, and pathlib.Path.is_symlink for filesystem traversal.

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.