Copying a symbolic link in Python

davidg picture davidg · Jan 31, 2011 · Viewed 17.6k times · Source

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?

Answer

Jochen Ritzel picture Jochen Ritzel · Jan 31, 2011

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.