How do I change a symlink to point from one file to another in Python?
The os.symlink
function only seems to work to create new symlinks.
No. The symlink system call will return EEXIST if newpath already exists. You can only link from a new node in the filesystem.
os. unlink() works for me. It removes the symlink without removing the directory that it links to.
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, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With