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
