How to Check if a Path is a Symbolic Link in Python
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.
Checking for Symlinks with pathlib
(Recommended)
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 aPath
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()
: ReturnsTrue
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 example
windows_path = Path(r'C:\Users\YourName\Documents\link_to_file.txt')
# or (using forward slashes works on Windows too)
windows_path = Path('C:/Users/YourName/Documents/link_to_file.txt')
# POSIX (Linux/macOS) path example:
posix_path = Path('/home/yourname/documents/link_to_file.txt')
Checking for Symlinks with os.path.islink()
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)
: ReturnsTrue
ifa_path
is a symbolic link,False
otherwise. Likepathlib.Path.is_symlink()
, this checks if the path itself is a symlink, not whether the target exists.
note
- On some systems,
os.path.islink()
might returnFalse
if the path has a trailing slash, even if it is a symbolic link to a directory. - Always remove trailing slashes before using
os.path.islink()
if you are not sure if it will be a file or a directory. You can do this withos.path.normpath()
or by usingpathlib
(pathlib
handles this correctly).