Modifying a symlink in python

Solution 1:

If you need an atomic modification, unlinking won't work.

A better solution would be to create a new temporary symlink, and then rename it over the existing one:

os.symlink(target, tmpLink)
os.rename(tmpLink, linkName)

You can check to make sure it was updated correctly too:

if os.path.realpath(linkName) == target:
    # Symlink was updated

According to the documentation for os.rename though, there may be no way to atomically change a symlink in Windows. In that case, you would just delete and re-create.

Solution 2:

A little function for Python2 which tries to symlink and if it fails because of an existing file, it removes it and links again. Check [Tom Hale's answer] for a up-to-date solution.

import os, errno

def symlink_force(target, link_name):
    try:
        os.symlink(target, link_name)
    except OSError, e:
        if e.errno == errno.EEXIST:
            os.remove(link_name)
            os.symlink(target, link_name)
        else:
            raise e

For python3 except condition should be except OSError as e:
[Tom Hale's answer]: https://stackoverflow.com/a/55742015/825924