LoginSignup
0
0

More than 1 year has passed since last update.

[Python]指定したフォルダ以下に含まれるファイルのハッシュ値を求め結果をテキストファイルに出力する

Posted at

はじめに

配布用ソフトのフォルダに含まれるファイルのハッシュ値計算に便利なので
以下の機能を持つ関数を作成しました。
・指定したフォルダ以下に含まれるファイルのハッシュ値(md5)を再帰的に求める
・結果をテキストファイルに出力する

ソース

  • 関数

md5.py
import hashlib
import os

def calcMd5(path):

    f = open('hashResult.txt', 'w')

    for root, dirs, files in os.walk(top = path):
        for file in files:
            filePath = os.path.join(root, file)
            # ファイル を バイナリーモード で開く
            with open(filePath, 'rb') as file:
                # ファイルを読み取る
                fileData = file.read()
                # md5ハッシュ値を計算する
                hash_md5 = hashlib.md5(fileData).hexdigest()
                #結果を標準出力、ファイル出力
                print(filePath + ' ' + hash_md5)
                f.write(filePath + ' ' + hash_md5 + '\n')
    f.close()
  • 呼び出し側

main.py
path = ".\sample"

import md5

md5.calcMd5(path)

結果

以下のようなフォルダ構成の場合
sample - sample1(1kB指定して作成した適当なファイル)
            └ sample2(1kB指定して作成した適当なファイル)
            └ test - sample1(1kB指定して作成した適当なファイル)
                       └ sample2(1kB指定して作成した適当なファイル)
など適当なサイズのファイルは
fsutil file createnew ファイル名 サイズ(バイト)
で作成出来る。

hashResult.txt
.\sample\sample1 6d0bb00954ceb7fbee436bb55a8397a9
.\sample\sample2 ede3d3b685b4e137ba4cb2521329a75e
.\sample\test\sample1 6d0bb00954ceb7fbee436bb55a8397a9
.\sample\test\sample2 ede3d3b685b4e137ba4cb2521329a75e

参考文献

Python - ファイルのハッシュ値を調べる
テキストファイルへ書き込む
Windowsで任意のサイズでファイルを作成する方法
MarkDown記法【初心者によるまとめ】
Python - 再帰的にサブフォルダ一覧とファイル一覧を取得する
【python】ファイル名、フォルダ名の一覧取得【osモジュール、globモジュール、再帰的な取得など】
【Python】絶対・相対パス取得・カレントディレクトリのアクセス方法|os・pathモジュールによるファイル操作入門

0
0
0

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