基于字典Python移动带有子文件夹的文件

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

我正在尝试找出一种更快的方法来复制和移动多个子文件夹中的 pdf 文件。我当前使用的代码将在主文件夹目录中的任何位置找到该文件,但是考虑到子文件夹和文件的数量,这需要很长时间。我当前的代码已将 Python 写入以下字母:

Python你好! 看到我发给你的列表中的最后一栏了吗?只需查看此位置的所有文件夹和子文件夹即可找到该 pdf 文件。当您这样做时,将其复制并移动到我发送给您的另一个位置。 慢慢来! 欣赏你, PyUser

我想写给Python的信:

亲爱的Python, 拿着这个清单。第一列是文件夹,第二列是子文件夹,最后一列是 pdf。 我将为您提供所有这些文件夹和子文件夹所在的位置。 到达该位置后,打开第一个文件夹,然后搜索第二个文件夹。 当您找到第二个文件夹时,打开该文件夹并搜索 pdf。 找到 pdf 后,复制一份并将其移至我发送给您的其他位置。 谢谢! PyUser

出于某种原因,我很难思考接下来的步骤。请告诉我您的专业知识(这里是相当新的 PyUser)?

我导入了一个列表,其中包含 .txt 中所需的文件:

TESTFOLDER_FROM0|TESTSUBFOLDER_FROM0|TEST1.pdf TESTFOLDER_FROM0|TESTSUBFOLDER_FROM0|TEST2.pdf TESTFOLDER_FROM1|TESTSUBFOLDER_FROM1|TEST3.pdf TESTFOLDER_FROM2|TESTSUBFOLDER_FROM2|TEST4.pdf TESTFOLDER_FROM3|TESTSUBFOLDER_FROM5|TEST5.pdf TESTFOLDER_FROM5|TESTSUBFOLDER_FROM8|TEST6.pdf TESTFOLDER_FROM637|TESTSUBFOLDER_FROM11|TEST7.pdf

这是工作蜗牛代码:

import csv
import os
import shutil

csv_path = input('Enter path to chart list text file: ')
csv_path = csv_path.replace("\\", "/")
csv_path = csv_path.replace("\"", "")

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

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

def find_file(base_path, file_name):
    for root, dirs, files in os.walk(base_path):
        if file_name in files:
            return os.path.join(root, file_name)
    return os.path.join(root, file_name)

find_file(base_path, csv_path)

with open(csv_path, 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='|')
    for row in csv_reader:
        print("CSV Row:", row)
        _, _, file_name = row
        file_path = find_file(base_path, file_name)
        if file_path:
            print("Found File Path:", file_path)
            print("Copying file to:", destination_path)
            shutil.copy(file_path, destination_path)
        else:
            print("File not found!")
python loops iteration shutil os.walk
1个回答
1
投票

您的问题描述相当难以理解,但基本问题似乎是您在同一文件树上重复运行

os.walk
。明显的优化是只运行一次,并让它查找您想要查找的所有文件。像这样的吗?

def find_em_all(paths, basedir):
    for root, subdirs, files in os.walk(basedir):
        keybase = os.path.split(root)[-2:-1]
         for file in files:
             pathtail = os.path.join(keybase, file)
             if pathtail in paths:
                 yield os.path.join(root, file)

这样称呼它

needles = [
    'one/wanted/path.pdf',
    'another/desired/file.pdf'
]
found = find_em_all(needles, '.')
© www.soinside.com 2019 - 2024. All rights reserved.