删除当前目录下内容相同的一个文件--Python脚本

删除当前目录下内容相同的一个文件--Python脚本

Southerly
2023-10-18 / 2 评论 / 108 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年10月18日,已超过205天没有更新,若内容或图片失效,请留言反馈。

使用说明:
1.需要有python环境
2.将脚本放在需要处理的文件夹里,双击运行就可以了
源码如下:

import os

# 获取当前目录下所有txt文件
def get_txt_files():
    files = []
    for file in os.listdir("."):
        if file.endswith(".txt"):
            files.append(file)
    return files

# 比较所有txt文件并删除相同的文件
def compare_and_delete():
    while True:
        txt_files = get_txt_files()
        deleted_files = set()  # 存储被删除的文件
        for i in range(len(txt_files)):
            if txt_files[i] in deleted_files:
                continue
            for j in range(i + 1, len(txt_files)):
                if txt_files[j] in deleted_files:
                    continue
                file1 = txt_files[i]
                file2 = txt_files[j]
                with open(file1, "r") as f1, open(file2, "r") as f2:
                    if f1.read() == f2.read():
                        os.remove(file2)
                        print("删除文件:", file2)
                        print("相同的文件:", file1, file2)
                        deleted_files.add(file2)
        if not deleted_files:  # 如果没有要删除的文件,则跳出循环
            break

# 执行脚本
compare_and_delete()

# 在处理完成后停留在命令窗口
raw_input()  # For Python 2
# input()  # For Python 3
本文共 109 个字数,平均阅读时长 ≈ 1分钟
2

海报

打赏

评论 (2)

语录
取消
  1. 头像
    Southerly 超V 作者
    Android · UC Browser 陕西省

    学习学习!

    回复 删除 垃圾
    1. 头像
      Southerly 超V 作者
      Windows 10 · Google Chrome 陕西省
      @ Southerly

      OωO

      回复 删除 垃圾