首页 > 解决方案 > Python - 将特定文件从子文件夹复制到目标,从文本文件中获取文件名

问题描述

我想让我的脚本从列表(txt)中读取名称列表,然后在带有子文件夹的选定文件夹中搜索那些名称,然后将这些文件复制并粘贴到另一个选定的文件夹中。我的脚本运行没有错误但没有结果。

我的脚本:

import os
import os.path
import shutil

textFile = ("D:\\Test\\list.txt")
sourceFolder = ("D:\\Test")
destinationFolder = ("D:\\")

filesToFind = []
with open(textFile, "r") as tx:
    for row in tx:
        filesToFind.append(row.strip())

for root, dirs, filename in os.walk(sourceFolder):
    if filename in filesToFind:
        f = os.path.join(root, filename)
        shutil.copy(f, destinationFolder)

标签: python

解决方案


没有测试它,但我认为这会起作用 - 改变这个:

for root, dirs, filename in os.walk(sourceFolder):
    if filename in filesToFind:
        f = os.path.join(root, filename)
        shutil.copy(f, destinationFolder)

对此:

for root, dirs, filenames in os.walk(sourceFolder):
    for filename in filenames:
        if filename in filesToFind:
            f = os.path.join(root, filename)
            shutil.copy(f, destinationFolder)

推荐阅读