Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a symlink in python

Tags:

python

symlink

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.

like image 917
meteoritepanama Avatar asked Nov 28 '11 16:11

meteoritepanama


People also ask

Can you edit a symlink?

No. The symlink system call will return EEXIST if newpath already exists. You can only link from a new node in the filesystem.

How do you remove a symbolic link in Python?

os. unlink() works for me. It removes the symlink without removing the directory that it links to.


2 Answers

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.

like image 74
lellimecnar Avatar answered Oct 06 '22 00:10

lellimecnar


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

like image 22
Robert Siemer Avatar answered Oct 06 '22 00:10

Robert Siemer