18

What I basically would like to do is cp -Rl dir1 dir2. But as I understand it, python only provides shutils.copytree(src,dst) which actually copies the files, but has no possibility of hardlinking the files instead.

I know that I could invoke the cp command using the subprocess module, but I'd rather like to find a cleaner (pythonic) way to do so.

So is there an easy way to do so or do I have to implement it myself recursing through the directories?

2
  • The directory traversal is pretty easy to do, so why not try it?
    – Blender
    May 28, 2012 at 3:09
  • 5
    It is not about trying or not trying: The question rather wants to say "I can't imagine that this hasn't been done before hundreds of times and therefore must be available in module xy". Reinventing the wheel all the time just doesn't seem right.
    – devsnd
    May 28, 2012 at 14:55

2 Answers 2

29

It's possible in Python stdlib using shutil and os.link:

import os, shutil

shutil.copytree(src, dst, copy_function=os.link)
2
  • 1
    @twall: Note this is Python 3 only. In Python 2, you might modify the example code: docs.python.org/library/shutil.html#copytree-example
    – Kabie
    May 29, 2012 at 1:16
  • It's not at all clear from the Python docs if copy_function=os.link actually exists, or need to be created artificially. (See examples in the linked docs.) If it does, then also os.symlink should be possible.
    – not2qubit
    Oct 19, 2020 at 20:35
7

Here's a pure python hardcopy function. Should work the same as cp -Rl src dst

import os
from os.path import join, abspath

def hardcopy(src, dst):
    working_dir = os.getcwd()
    dest = abspath(dst)
    os.mkdir(dst)
    os.chdir(src)
    for root, dirs, files in os.walk('.'):
        curdest = join(dst, root)
        for d in dirs:
            os.mkdir(join(curdst, d))
        for f in files:
            fromfile = join(root, f)
            to = join(curdst, f)
            os.link(fromfile, to)
    os.chdir(working_dir)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.