(May-18-2024, 05:44 PM)Skaperen Wrote: many functions call with a file system path can also choose whether to follow symlinks (usually the default) or not. is there a way to make this choice with os.listdir()?
os.listdir
does not distinguish between regular files and symbolic links.With
os.scandir
can check if an entry is a symbolic linkThis allows you to manually choose whether to follow symbolic links or not.
import os with os.scandir('path/to/directory') as it: for entry in it: if entry.is_symlink(): print(f"{entry.name} is a symbolic link") else: print(entry.name)Pathlib also has a
resolve
(returns the absolute path of the target file or directory).Follows all levels of symlinks until it reaches the final target.
from pathlib import Path path = Path('path/to/symlink') if path.is_symlink(): target_path = path.resolve() print(f"{path} points to {target_path}") else: print(f"{symlink_path} is not a symbolic link")