devsnd
devsnd

Reputation: 7722

Recursively creating hardlinks using python

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?

Upvotes: 22

Views: 7422

Answers (2)

Kabie
Kabie

Reputation: 10663

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

import os, shutil

shutil.copytree(src, dst, copy_function=os.link)

Upvotes: 34

Damien Ayers
Damien Ayers

Reputation: 1629

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)

Upvotes: 7

Related Questions