Search code examples
pythonpython-3.xsymlink

How to find out if a symbolic link points to a missing directory?


I have a symbolic link to a directory that does not exist:

~/ramdisk -> /dev/shm/mydir

When running my Python code, I get the error:

FileNotFoundError: [Errno 2] No such file or directory: '~/ramdisk'

How can I avoid this error, detecting beforehand the fact the directory is missing?

The only method I found is symlink(), which creates a symbolic link.


Solution

  • The whole point of symlinks is that ~/ramdisk is treated essentially the same as /dev/shm/mydir would be unless you are doing symlink specific operations.

    import os
    os.path.exists('~/ramdisk')
    # or, as suggested by Stephen:
    from pathlib import Path
    Path('~/ramdisk').is_dir()
    

    would all be the same as if you used checked /dev/shm/mydir instead.