使用python递归创建硬链接

问题描述 投票:0回答:2

我基本上想做的是

cp -Rl dir1 dir2
。但据我了解,python 只提供了
shutils.copytree(src,dst)
,它实际上复制了文件,但不可能硬链接文件。

我知道我可以使用

cp
模块调用
subprocess
命令,但我宁愿找到一种更干净(Pythonic)的方法来执行此操作。

那么有没有一种简单的方法可以做到这一点,或者我必须自己通过目录递归来实现它?

python directory directory-structure hardlink
2个回答
27
投票

它可以在模块中使用

shutil
:

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

7
投票

这是一个纯Python硬拷贝函数。应该和

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)
© www.soinside.com 2019 - 2024. All rights reserved.