python批量读取文件中的文件名并删除

技术分享 2025-12-08

python批量读取txt文件中的文件名(一行一个),并删除当前目录中的这些文件。

import os
import sys

def delete_files_from_txt(txt_file_path="file_delete.txt"):
    # 第一步:校验TXT文件是否存在(优先当前目录)
    txt_abs_path = os.path.abspath(txt_file_path)
    if not os.path.exists(txt_abs_path):
        print(f"错误:未找到TXT文件 → {txt_abs_path}")
        return

    # 第二步:读取TXT中的文件名(每行一个,保留-开头的完整名称)
    try:
        with open(txt_abs_path, 'r', encoding='utf-8') as f:
            # 读取所有行,去除空行和首尾空白(不修改文件名本身的-开头)
            file_list = [line.strip() for line in f if line.strip()]
    except Exception as e:
        print(f"错误:读取TXT文件失败 → {e}")
        return

    if not file_list:
        print("提示:TXT文件中未找到任何有效文件名")
        return

    # 第三步:遍历删除(重点处理-开头的文件,避免被误判为参数)
    deleted_count = 0
    failed_count = 0
    print(f"开始处理,共找到 {len(file_list)} 个文件待删除:\n")

    for index, filename in enumerate(file_list, 1):
        # 拼接当前目录下的绝对路径(确保-开头的文件名被正确识别为路径)
        file_abs_path = os.path.abspath(os.path.join(os.getcwd(), filename))

        # 检查文件是否存在
        if not os.path.exists(file_abs_path):
            print(f"[{index}] 跳过 → 文件不存在:{file_abs_path}")
            failed_count += 1
            continue

        # 仅删除文件,跳过目录(防止误删文件夹)
        if os.path.isdir(file_abs_path):
            print(f"[{index}] 跳过 → 是目录,不删除:{file_abs_path}")
            failed_count += 1
            continue

        # 核心:处理-开头的文件(使用完整绝对路径,避免系统误判)
        try:
            os.remove(file_abs_path)
            print(f"[{index}] 成功 → 删除文件:{file_abs_path}")
            deleted_count += 1
        except PermissionError:
            print(f"[{index}] 失败 → 权限不足:{file_abs_path}")
            failed_count += 1
        except Exception as e:
            print(f"[{index}] 失败 → 原因:{str(e)} | 文件:{file_abs_path}")
            failed_count += 1

    # 第四步:输出汇总结果
    print("\n" + "-"*50)
    print(f"处理完成 → 成功删除:{deleted_count} 个 | 删除失败:{failed_count} 个")

if __name__ == "__main__":
    # 直接运行脚本即可(默认读取当前目录下的file_delete.txt)
    delete_files_from_txt()

请使用python3运行该脚本。

评论 (0)

发表评论

最多500字符

验证码

暂无评论

成为第一个评论的人吧!