Python 实现 一个基于 TXT 文本列表的批量文件移动工具

flyfish

读取一个 TXT 文件里写好的所有源文件路径,然后把这些文件统一剪切并粘贴到一个指定的目标文件夹中。

批量移动文件:利用 shutil.move 将分散在各个路径下的文件,统一移动到指定的 TARGET_FOLDER 中。
按清单执行:不扫描整个硬盘,而是严格按照 TXT_FILE_PATH 中记录的路径一行一行地去执行
Linux下使用的代码

import os
import shutil

# ===================== 【只需改这里】 =====================
# txt 文件路径(里面每行是一个文件绝对路径)
TXT_FILE_PATH = r"/media/user/xxx/normal.txt"

# 要剪切到的目标文件夹
TARGET_FOLDER = r"/media/user/xxx/target_normal"

# 是否覆盖已存在的文件(True=覆盖,False=跳过)
OVERWRITE = False
# =================================================================

def move_files_from_txt(txt_path, target_dir, overwrite=False):
    # 1. 创建目标文件夹(不存在则创建)
    os.makedirs(target_dir, exist_ok=True)
    print(f"目标文件夹已准备:{target_dir}")

    # 2. 读取 txt 所有行
    with open(txt_path, "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f.readlines() if line.strip()]

    total = len(lines)
    success = 0
    fail = 0
    skip = 0

    print(f"\n开始剪切,共 {total} 个文件...\n")

    # 3. 遍历剪切
    for i, src_path in enumerate(lines, 1):
        filename = os.path.basename(src_path)
        dst_path = os.path.join(target_dir, filename)

        # 检查源文件是否存在
        if not os.path.exists(src_path):
            print(f"[{i}/{total}] 不存在:{src_path}")
            fail += 1
            continue

        # 目标已存在
        if os.path.exists(dst_path):
            if overwrite:
                print(f"[{i}/{total}] 覆盖:{filename}")
            else:
                print(f"[{i}/{total}] 已存在,跳过:{filename}")
                skip += 1
                continue

        # 执行剪切
        try:
            shutil.move(src_path, dst_path)
            print(f"[{i}/{total}] 剪切成功:{filename}")
            success += 1
        except Exception as e:
            print(f"[{i}/{total}] 剪切失败:{filename} | 错误:{str(e)}")
            fail += 1

    # 4. 统计
    print("\n" + "="*50)
    print(f"剪切完成!")
    print(f"总计:{total}")
    print(f"成功:{success}")
    print(f"跳过:{skip}")
    print(f"失败:{fail}")
    print("="*50)

if __name__ == "__main__":
    move_files_from_txt(TXT_FILE_PATH, TARGET_FOLDER, OVERWRITE)

如果要在 Windows 下完美实现覆盖,可以在 shutil.move 前加一句判断:

if overwrite and os.path.exists(dst_path):
    os.remove(dst_path) # 先删除已存在的旧文件,再执行 move
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐