Modifying a symlink in python Modifying a symlink in python python python

Modifying a symlink in python


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.


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, errnodef 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


You could os.unlink() it first, and then re-create using os.symlink() to point to the new target.