0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python|同じファイルをコピーして大量のファイルを整理してくれるプログラム

Last updated at Posted at 2023-03-21

同じファイルをコピーして大量のファイルを整理してくれるプログラム

はじめに

ファイル整理に役立つようなソースコードを作ろうと思いました。
まずは、一番使えそうな どうフォルダー内の同じファイル消してくれるPythonのサンプルプログラムです

Python:removeSameFile.py

import os
import hashlib

def get_file_hash(file_path):
    """
    ファイルのハッシュ値を計算する関数
    :param file_path: ファイルパス
    :return: ファイルのハッシュ値
    """
    try:
        with open(file_path, "rb") as f:
            file_hash = hashlib.md5()
            while chunk := f.read(8192):
                file_hash.update(chunk)
            return file_hash.hexdigest()
    except FileNotFoundError:
        return None

def delete_duplicate_files(folder_path):
    """
    重複したファイルを削除する関数
    :param folder_path: フォルダパス
    """
    delete_count = 0
    total_count = 0
    hashes = {}
    for dirpath, dirnames, filenames in os.walk(folder_path):
        for filename in filenames:
            file_path = os.path.join(dirpath, filename)
            file_hash = get_file_hash(file_path)
            if file_hash is None:
                continue
            if file_hash in hashes:
                os.remove(file_path)
                delete_count += 1
            else:
                hashes[file_hash] = file_path
            total_count += 1
    print(f"削除したファイル数: {delete_count}/{total_count}")

if __name__ == "__main__":
    folder_path = "./"
    delete_duplicate_files(folder_path)


実行してみよう

Python:コマンドプロンプト.
# python3 removeSameFile.py
# 削除したファイル数: 914/916

下の部分は、今いるフォルダー内のファイル対象になります

Python:removeSameFile.py
    folder_path = "./"

folder_path に 消したいフォルダーの位置を指定してください。

ファイルが消されてしまいますので、念の為に新しいフォルダーを作りその中の不必要になったファイルをコピーを何回かして試してみてください。

おわりに

割とゴミみたいなファイルがいっぱいあるんだなと思いますね。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?