按照指定文件名移到文件
简介
假设目录与文件如下:
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)
❤️ 转载文章请注明出处,谢谢!❤️