博主头像 Southerly 博主 4月24日 在线

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

  • Southerly 2023年10月18日 587阅读 2评论
  • AI摘要:此Python脚本用于删除当前目录下内容相同的txt文件。脚本运行后,会自动比较所有txt文件,并删除内容重复的文件,最后停留在命令窗口。

    🍂🍁Southerly🍁🍂

    使用说明:
    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
    打赏

    —— 评论区 ——

    昵称
    邮箱
    网址
    取消
    1. 头像
      Southerly 博主
      Android 13   WebView 537 陕西省
      回复

      学习学习!

      1. 头像
        Southerly 博主
        Windows 10 x64 Edition   Microsoft Edge 119 陕西省
        回复
        @Southerly

        OωO

    站点公告

    请勿在本站点发表不当言论,以及进行恶意引流行为,否则会对该ip进行封禁处理

      2024年还剩下:
      0 64 11小时 35 35


    人生倒计时
    舔狗日记