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?
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.
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.
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.
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.
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.
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