从文件夹(包含子文件夹)找到的包含特定关键词的 Word 文档复制到一个新的文件夹中

python 复制代码
import os
import glob
import shutil

def find_and_copy_docs(root_dir, keyword, target_dir):
    """
    在指定的目录及其子目录下查找包含特定关键词的 Word 文档,并将它们复制到目标文件夹。

    参数:
    root_dir: 要搜索的根目录路径。
    keyword: 需要匹配的关键词。
    target_dir: 复制到的目标文件夹路径。
    """
    # 为了匹配包含关键词的文件名,构建一个搜索模式
    pattern = f"*{keyword}*.docx"

    # 确保目标文件夹存在
    os.makedirs(target_dir, exist_ok=True)

    # 存储找到的文件的列表
    found_files = []

    # 遍历 root_dir 下的所有目录和子目录
    for dirpath, dirnames, filenames in os.walk(root_dir):
        # 在当前目录下查找匹配模式的文件
        for filename in glob.glob(os.path.join(dirpath, pattern)):
            found_files.append(filename)
            # 复制文件到目标文件夹
            shutil.copy(filename, target_dir)
    
    return found_files

# 使用示例
root_directory = 'path/to/your/directory'  # 请替换为你的目录路径
keyword = '题目总和'
target_directory = 'path/to/target/directory'  # 目标文件夹路径,请替换为你的目标路径
matching_files = find_and_copy_docs(root_directory, keyword, target_directory)

# 打印结果
print("找到并复制的包含关键词的 Word 文档:")
for file in matching_files:
    print(file)

这个脚本现在包含了一个 find_and_copy_docs 函数,它接收一个目标文件夹路径作为额外的参数。在找到符合条件的 Word 文档后,脚本使用 shutil.copy 函数将每个文档复制到指定的目标文件夹中。如果目标文件夹不存在,os.makedirs(target_dir, exist_ok=True) 语句将会创建它。

请确保将 root_directory 和 target_directory 变量替换为你想要搜索的实际目录路径和你希望复制文件到的目标文件夹路径。运行脚本后,所有匹配的文件都会被复制到指定的目标文件夹中,同时在控制台打印出这些文件的路径。

相关推荐
随性而行3602 分钟前
企业微信二次开发如何接入大模型工具?API接口实现智能任务调用的技术思路
java·前端·人工智能·python·微信·机器人·企业微信
2601_966949659 分钟前
量化回测中分钟数据应该如何保存?从文件到数据仓库的工程化设计
开发语言·python·pandas·量化交易·股票数据·quantdash
huisheng_qaq20 分钟前
【Python基础篇-05】深入理解python的异常处理与文件读写
python·异常处理·文件读写
Zhou14113623 分钟前
SpringMVC_02_注解开发实战
开发语言·windows·python
温暖小土26 分钟前
Spring AI 接入 DeepSeek Chat 模型
数据库·人工智能·spring
张小姐的猫31 分钟前
【AI大模型接入SDK】 —— 前端页面 & 项目总结与拓展
前端·数据结构·数据库·c++·人工智能·chatgpt
IvorySQL33 分钟前
去 IOE 的最后一公里:IvorySQL 5.4 × RISC-V 实测
数据库·人工智能·ai·postgresql·risc-v
-madongyu-40 分钟前
HCIE-GaussDB V2.0 笔试考点总览:模块权重、核心要点与高频数字速记
数据库·华为·gaussdb
禹凕42 分钟前
机器学习之数据清洗(Machine Learning about Data Cleaning)
人工智能·爬虫·python·机器学习·数据挖掘