Skip to content

How to Check if a Path is a Symbolic Link in Python

Learn how to verify whether a given path in Python is a symbolic link using the modern pathlib.Path.is_symlink() method or the traditional os.path.islink() function.

Symbolic links (symlinks) are special files that act as pointers to other files or directories.

This guide explains how to check if a given path in Python points to a symbolic link, using both the modern pathlib module (recommended) and the older os.path module.

The pathlib module (introduced in Python 3.4) provides an object-oriented way to interact with files and directories. It's generally the preferred way to work with paths in modern Python. The Path.is_symlink() method directly checks if a path is a symbolic link:

from pathlib import Path

path = Path(r'/home/tomnolan/Desktop/python/src')  # Replace with your path

if path.is_symlink():
    print('The given path points to a symbolic link')
else:
    print('The path does NOT point to a symbolic link')
  • Path(r'/your/path/here'): Creates a Path object representing the file or directory. Use a raw string (r'...') on Windows to avoid issues with backslashes, or use forward slashes.
  • path.is_symlink(): Returns True if the path is a symbolic link, False otherwise. This works even if the target of the symlink doesn't exist. It checks the file type, not the target's existence.

Here is how you can declare paths on Windows and POSIX operating systems:

windows_path = Path(r'C:\Users\YourName\Documents\link_to_file.txt')
windows_path = Path('C:/Users/YourName/Documents/link_to_file.txt')

posix_path = Path('/home/yourname/documents/link_to_file.txt')

The os.path module provides a more traditional way to check for symlinks using the islink() function:

import os.path

a_path = r'/home/tomnolan/Desktop/python/src'

if os.path.islink(a_path):
    print('The given path points to a symbolic link')
else:
    print('The path does NOT point to a symbolic link')
  • os.path.islink(a_path): Returns True if a_path is a symbolic link, False otherwise. Like pathlib.Path.is_symlink(), this checks if the path itself is a symlink, not whether the target exists.
Navigation