pathlib.Path.exists returns False for broken symlink
01:37 14 Feb 2023

Consider this setup in a command line:

touch test.txt
ln -s test.txt test.lnk
rm test.txt

So we have a broken symlink that points to deleted file. Now in Python:

import pathlib
p = pathlib.Path('test.lnk')
p.is_symlink()  # True
p.exists()  # False

Python tells me that "test.lnk is a symlink, but it doesn't exist..."
Because of that I am not able to check correctly if there is something named test.lnk in a directory:

if not p.exists():
    p.symlink_to('another_file')
# Traceback (most recent call last):
#   File "", line 1, in 
#   File "/usr/lib/python3.8/pathlib.py", line 1384, in symlink_to
#     self._accessor.symlink(target, self, target_is_directory)
#   File "/usr/lib/python3.8/pathlib.py", line 446, in symlink
#     return os.symlink(a, b)
# FileExistsError: [Errno 17] File exists: 'another_file' -> 'test.lnk'

How do I work around that? What is the correct way to check if a broken symlink exists in Python?

python linux symlink