Python Forum
os.listdir() and follow_symlinks
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
os.listdir() and follow_symlinks
#4
(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 link
This 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")
Reply


Messages In This Thread
os.listdir() and follow_symlinks - by Skaperen - May-18-2024, 05:44 PM
RE: os.listdir() and follow_symlinks - by Skaperen - May-23-2024, 12:51 AM
RE: os.listdir() and follow_symlinks - by snippsat - May-23-2024, 05:08 AM
RE: os.listdir() and follow_symlinks - by bowlofred - May-23-2024, 07:05 AM
RE: os.listdir() and follow_symlinks - by Skaperen - May-24-2024, 03:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  short version of os.listdir() Skaperen 12 914 May-30-2024, 03:06 AM
Last Post: Skaperen
  listdir on IP Adress OEMS1 3 3,068 Jul-19-2020, 06:01 PM
Last Post: bowlofred
  trouble with os.listdir on a network drive lconner 10 19,623 Jun-04-2019, 07:16 PM
Last Post: DeaD_EyE
  os.listdir(path) and non-string as input metalray 4 17,144 Aug-15-2018, 11:43 AM
Last Post: metalray
  listdir trouble Dixon 1 2,752 Jan-17-2018, 11:32 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020