按照文本每行匹配文件复制到指定位置

1

  • 从指定的 TXT 文件(txt_file)中读取若干关键字(去重并按字典序排序)。

  • 在给定的源目录(source_dir)及其子目录中,查找文件名包含某关键字的第一个文件。

  • 将该文件移动到目标目录(target_dir),并在遇到重名时自动添加后缀 _1, _2… 以免覆盖。

  • 控制台实时输出每个关键字的匹配与移动结果,最后汇总共多少关键字、成功移动多少个文件。

1

假设目录与文件如下:

H:\
├─ data
│   ├─ report1.txt
│   ├─ image_fail.png
│   └─ sub
│       └─ test_error.log
├─ list.txt
└─ copy    (初始为空)

list.txt 内容(每行一个关键字)

report
fail
missing
error

运行控制台输出

✔ 已移动: 'report1.txt' 对应关键字 'report' 到 'H:\copy\report1.txt'
✔ 已移动: 'image_fail.png' 对应关键字 'fail' 到 'H:\copy\image_fail.png'
⚠ 未找到匹配文件 for key: 'missing'
✔ 已移动: 'test_error.log' 对应关键字 'error' 到 'H:\copy\test_error.log'

共 4 个关键字,成功移动 3 个,对应文件。未移动 1 个。

执行后目录结构

H:\
├─ data
│   └─ sub
│       └─               (原 test_error.log 已移动)
├─ copy
│   ├─ report1.txt
│   ├─ image_fail.png
│   └─ test_error.log
├─ list.txt

import os
import shutil

def move_files_from_txt(txt_file, source_dir, target_dir):
    """
    仅移动文件名中包含 TXT 文件中任意一行关键字的文件。
    如果某关键字未匹配任何文件,会在控制台报告。
    """
    # 创建目标目录
    os.makedirs(target_dir, exist_ok=True)

    # 读取并去重 TXT 关键字
    with open(txt_file, 'r', encoding='utf-8') as f:
        keys = sorted({line.strip() for line in f if line.strip()})

    moved_keys = set()
    # 对每个关键字,查找并移动第一个匹配的文件
    for key in keys:
        found = False
        for root, _, files in os.walk(source_dir):
            for fname in files:
                if key in fname:
                    # 构造路径
                    src = os.path.join(root, fname)
                    dst = os.path.join(target_dir, fname)
                    # 处理重名
                    if os.path.exists(dst):
                        base, ext = os.path.splitext(fname)
                        i = 1
                        while os.path.exists(os.path.join(target_dir, f"{base}_{i}{ext}")):
                            i += 1
                        dst = os.path.join(target_dir, f"{base}_{i}{ext}")
                    # 移动
                    shutil.move(src, dst)
                    print(f"✔ 已移动: '{fname}' 对应关键字 '{key}' 到 '{dst}'")
                    moved_keys.add(key)
                    found = True
                    break
            if found:
                break
        if not found:
            print(f"⚠ 未找到匹配文件 for key: '{key}'")

    total = len(keys)
    success = len(moved_keys)
    print(f"\n共 {total} 个关键字,成功移动 {success} 个,对应文件。未移动 {total - success} 个。")

# 示例使用
if __name__ == '__main__':
    txt_file = r"H:\list.txt"
    source_directory = r"H:\data"
    target_directory = r"H:\copy"
    move_files_from_txt(txt_file, source_directory, target_directory)

1

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值