从文件夹(包含子文件夹)找到的包含特定关键词的 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 变量替换为你想要搜索的实际目录路径和你希望复制文件到的目标文件夹路径。运行脚本后,所有匹配的文件都会被复制到指定的目标文件夹中,同时在控制台打印出这些文件的路径。

相关推荐
知行合一。。。33 分钟前
Python--04--数据容器(总结)
开发语言·python
架构师老Y37 分钟前
008、容器化部署:Docker与Python应用打包
python·容器·架构
lifewange1 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
等....1 小时前
Minio使用
数据库
pluvium271 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499992 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉2 小时前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi2 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^2 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
win x2 小时前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis