Mostly Linux & Python syntax notes and hyperlinks.

Wednesday, May 25, 2011

Python: os.path.lexists() vs os.path.exists() before os.symlink()

We were having intermittent failures with shutil.copy(src,dest) and decided to replace it with just a symbolic link, using os.symlink(src,dest). This triggered an error when we tried to create a symbolic link with the name of an existing file. So the code checks first. It uses os.path.lexists(), since that will return True for broken as well as valid links. os.path.exists() returns True for valid links, False for broken ones.
The os.remove() works whether or not the link is broken or valid or an actual file.
if os.path.lexists(dest):
    os.remove(dest)
os.symlink(src,dest)
(For more detail, see also June2013)

No comments:

Post a Comment