linux中,使用python3 实现用硬链接的方式复制复合文件夹
copy_with_hardlink.py
import os
import argparse
def copy_with_hardlinks(src, dst):
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
src_item = os.path.join(src, item)
dst_item = os.path.join(dst, item)
if os.path.isdir(src_item):
# 递归处理子目录
copy_with_hardlinks(src_item, dst_item)
else:
# 创建硬链接
print(f"硬链接: {src_item} -> {dst_item}")
if os.path.exists(dst_item):
os.remove(dst_item)
os.link(src_item, dst_item)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="复制文件夹并创建硬链接")
parser.add_argument("source", help="源文件夹路径")
parser.add_argument("destination", help="目标文件夹路径")
args = parser.parse_args()
src_path = args.source
dst_path = args.destination
if os.path.exists(src_path):
copy_with_hardlinks(src_path, dst_path)
print(f"复制完成:{src_path} -> {dst_path}")
else:
print(f"源文件夹不存在:{src_path}")
使用说明
-
将上述脚本保存到一个Python文件中,例如 copy_with_hardlinks.py。
-
打开终端并导航到脚本所在目录。
-
运行脚本并指定源文件夹和目标文件夹:
python3 copy_with_hardlinks.py /path/to/source_directory /path/to/destination_directory
假设你有如下结构的源目录:
source_directory/
├── subdir1/
│ ├── file1.txt
│ └── file2.txt
└── subdir2/
└── file3.txt
运行脚本后,目标目录将变为:
destination_directory/
├── subdir1/
│ ├── file1.txt (硬链接)
│ └── file2.txt (硬链接)
└── subdir2/
└── file3.txt (硬链接)
注意事项
-
硬链接只能在同一个文件系统内创建,所以源目录和目标目录必须位于相同的文件系统中。(注意,也不能跨磁盘)
-
硬链接的创建需要有相应的权限,确保在运行脚本时具有足够的权限。
-
目标目录中的文件如果已经存在,会被先删除以避免创建硬链接时的冲突。
以上脚本可以实现递归复制文件夹,并在复制文件时创建硬链接,相当于 cp -r 并使用硬链接的效果。
以上内容来源于chatgpt, 经过试验确认,复制迅速准确。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2021-10-25 linux scp自动填充密码脚本