使用python递归创建硬链接

dev*_*snd 14 python directory directory-structure hardlink

我基本上想做的是cp -Rl dir1 dir2.但据我了解,python只提供shutils.copytree(src,dst)实际复制文件的内容,但不可能将文件硬链接.

我知道我可以cp使用subprocess模块调用命令,但我更愿意找到一种更干净(pythonic)的方法.

那么有一个简单的方法可以这样做,还是我必须自己通过目录递归来实现它?

Kab*_*bie 20

你只需要打电话os.system("cp -Rl dir1 dir2"),不需要手写你自己的功能.

编辑:因为你想在python中这样做.

你是对的:它在模块中可用 shutil

shutil.copytree(src, dst, copy_function=os.link)
Run Code Online (Sandbox Code Playgroud)


Dam*_*ers 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)
Run Code Online (Sandbox Code Playgroud)