Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a symbolic link in Python

Tags:

I want to copy a file src to the destination dst, but if src happens to be a symbolic link, preserve the link instead of copying the contents of the file. After the copy is performed, os.readlink should return the same for both src and dst.

The module shutil has several functions, such as copyfile, copy and copy2, but all of these will copy the contents of the file, and will not preserve the link. shutil.move has the correct behavior, other than the fact it removes the original file.

Is there a built-in way in Python to perform a file copy while preserving symlinks?

like image 536
davidg Avatar asked Jan 31 '11 04:01

davidg


People also ask

How do I copy a symbolic link in Python?

In Python 3, most copy methods of shutil have learned the follow_symlinks argument, which preserves symlinks if selected. Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src.

How do you copy a symbolic link?

We can use the -l option of rsync for copying symlinks. rsync copies the symlinks in the source directory as symlinks to the destination directory using this option. Copying the symlinks is successful in this case.

How do you create a symbolic link in Python?

symlink() method in Python is used to create symbolic link. This method creates symbolic link pointing to source named destination. To read about symbolic links/soft links, please refer to this article.

Does SCP copy symbolic links?

it's not possible - scp will follow symbolic links when used with the -r option. To copy symbolic links as symbolic links you need to use f.e. rsync or similar.


1 Answers

Just do

def copy(src, dst):     if os.path.islink(src):         linkto = os.readlink(src)         os.symlink(linkto, dst)     else:         shutil.copy(src,dst) 

shutil.copytree does something similar, but as senderle noted, it's picky about copying only directories, not single files.

like image 198
Jochen Ritzel Avatar answered Oct 11 '22 17:10

Jochen Ritzel