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

Python如何递归查找匹配列表任意字符串的文件并拷贝到目标目录

问题原因与解决方案

错误原因

  • os.walk返回的第三个参数是当前遍历目录下所有文件名组成的列表,你直接对该列表做字符串包含判断,才会触发「预期传入字符串而非列表」的类型错误,你用到的any()函数本身语法是正确的。
  • 直接传文件名给shutil.copy会找不到非当前工作目录下的文件,需要拼接遍历到的根路径得到完整的文件路径。
  • 原代码for循环末尾缺少冒号,存在语法错误。

优化实现方案

方案1:基于os.walk的最简修正

import os
import shutil

source_dir = "替换为你的源目录路径"
destination_dir = "替换为你的目标目录路径"
string_to_match = ['apple.txt', 'pear.txt', 'banana.txt']

# 提前创建目标目录,避免路径不存在报错
os.makedirs(destination_dir, exist_ok=True)

# 不需要用到的子目录列表可以用_占位
for root, _, filenames in os.walk(source_dir):
    # 遍历当前目录下的所有单个文件
    for filename in filenames:
        # 匹配逻辑:文件名包含列表中任意字符串
        if any(s in filename for s in string_to_match):
            # 拼接得到文件的完整路径
            src_full_path = os.path.join(root, filename)
            shutil.copy(src_full_path, destination_dir)
            print(f"已拷贝文件:{src_full_path}")

如果你需要的是精确匹配文件名完全等于列表中的某个值,可以把判断逻辑改成if filename in string_to_match,比字符串包含判断效率更高,也不会误匹配到包含目标字符串的其他文件。

方案2:基于glob的递归多匹配实现

如果偏好更简洁的写法,可以用glob的递归遍历能力实现需求:

import os
import glob
import shutil

source_dir = "替换为你的源目录路径"
destination_dir = "替换为你的目标目录路径"
string_to_match = ['apple.txt', 'pear.txt', 'banana.txt']

os.makedirs(destination_dir, exist_ok=True)

# 递归遍历源目录下的所有路径
for file_path in glob.glob(f"{source_dir}/**/*", recursive=True):
    # 跳过目录,只处理文件
    if not os.path.isfile(file_path):
        continue
    filename = os.path.basename(file_path)
    if any(s in filename for s in string_to_match):
        shutil.copy(file_path, destination_dir)
        print(f"已拷贝文件:{file_path}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 09:18:00