You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于路径列表的多子文件夹PDF快速迁移Python实现求助

高效文件迁移方案优化

核心优化逻辑

你的原代码每次查找单个文件都通过os.walk遍历整个目录树,当文件/文件夹数量庞大时,重复遍历会导致效率极低。现在我们直接利用txt列表中的路径层级信息,直接拼接目标文件的完整路径,彻底跳过遍历步骤,大幅提升迁移速度。

修改后的完整代码

import os
import shutil

# 获取输入路径并统一格式处理
csv_path = input('Enter path to chart list text file: ')
csv_path = csv_path.replace("\\", "/").strip('"')

base_path = input('Enter base path where charts are to be copied FROM: ')
base_path = base_path.replace("\\", "/").strip('"')

destination_path = input('Enter path where the files should be copied TO: ')
destination_path = destination_path.replace("\\", "/").strip('"')

# 确保目标目录存在,不存在则自动创建
os.makedirs(destination_path, exist_ok=True)

# 读取路径列表并处理文件复制
with open(csv_path, 'r', encoding='utf-8') as txt_file:
    for line in txt_file:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        
        # 按分隔符拆分路径片段
        parts = line.split('|')
        if len(parts) != 3:
            print(f"无效行格式,跳过: {line}")
            continue
        
        main_folder, sub_folder, file_name = parts
        # 拼接源文件完整路径(自动适配系统路径分隔符)
        source_file = os.path.join(base_path, main_folder, sub_folder, file_name)
        
        # 验证文件存在性后执行复制
        if os.path.isfile(source_file):
            print(f"复制: {source_file} -> {destination_path}")
            shutil.copy2(source_file, destination_path)  # 保留文件元数据
        else:
            print(f"文件不存在,跳过: {source_file}")

关键改进点

  • 移除低效遍历:彻底删除os.walk相关逻辑,直接通过路径片段拼接定位文件,时间复杂度从O(n*m)降至O(n)(n为文件数量,m为目录层级数)。
  • 路径处理更可靠:用os.path.join自动适配Windows/macOS/Linux的路径分隔符,替代手动替换的粗糙方式;用strip('"')简化引号清理。
  • 鲁棒性提升:自动创建目标目录、跳过空行和格式错误的行,避免程序中途崩溃。
  • 保留文件元数据:改用shutil.copy2替代shutil.copy,复制时保留文件的创建时间、修改时间等元数据,更符合迁移场景需求。

注意事项

  • 确保txt列表中的路径层级与实际文件系统完全匹配(Linux/macOS区分大小写,Windows不区分)。
  • 若目标目录存在同名文件,shutil.copy2会直接覆盖;如需避免覆盖,可在复制前添加os.path.exists(dest_file)的判断逻辑,实现重命名或跳过操作。

内容的提问来源于stack exchange,提问作者NerdBurgler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 01:28:15