使用python递归创建硬链接

2024-04-27 17:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上想做的是cp -Rl dir1 dir2。但据我所知,python只提供了shutils.copytree(src,dst),它实际上复制了文件,但没有硬链接文件的可能。在

我知道我可以使用subprocess模块来调用cp命令,但我更希望找到一种更干净(pythonic)的方法。在

那么有没有一种简单的方法来实现呢?或者我必须自己通过目录递归实现它?在


Tags: 模块文件方法命令src链接pythoniccp
2条回答

这是一个纯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)

您只需调用os.system("cp -Rl dir1 dir2"),不需要手工编写自己的函数。在

已编辑:因为您希望在python中执行此操作。在

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

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

相关问题 更多 >