LoginSignup
1
1

More than 5 years have passed since last update.

Python手遊び(ファイルリスト/Hash演算)

Last updated at Posted at 2019-01-19

この記事、何?

ちょっとした小ネタでpythonスクリプトを2種類3つ。
■ファイルリスト
指定フォルダ以下のファイルのリストを作成(ファイル所在パス + '\t' + ファイル名)

■ハッシュ演算
文字列もしくはファイルを渡してそのHash値を出力

どういう人向け?

まあ、自分あて。
ペタッとコピペして使えるので良ければどうぞ。

試した環境は?

Windows 8 Pro
Python 3.6.8 (conda version 4.5.12)

コード

ファイルリスト [12-01.py]

仕様:引数でもらったフォルダ以下のファイルを出力する

12-01.py
#Usage:
#    python 12-01.py (targetfolder)

import sys
import os
target=sys.argv[1]
print('---------------------------------------------------------')
print(target)
print('---------------------------------------------------------')
for dirpath, dirs, files in os.walk(target):
    for name in files:
        print(dirpath + '\t' + name)

Hash演算(その1) [12-02.py]

仕様:引数でもらった文字列のHash値を演算する

12-02.py
#Usage:
#    python 12-02.py (targetfile)

import sys
import hashlib
target=sys.argv[1]
print('---------------------------------------------------------')
print(target)
print('---------------------------------------------------------')
print(hashlib.md5(target.encode()).hexdigest())

Hash演算(その2) [12-03.py]

仕様:引数でもらったファイルのHash値を演算する

#Usage:
#    python 12-03.py (targetfile)

import sys
import hashlib
target=sys.argv[1]
print('---------------------------------------------------------')
print(target)
print('---------------------------------------------------------')
with open(target, 'rb') as f:
    checksum = hashlib.md5(f.read()).hexdigest()
    print(checksum)

補足

HashはとりあえずMD5にしているけど、そのままSHA256とかに変更可能。
if文書いてもよかったんだけど、全文が短いからこのままでいいかな、と。
よく、ずらっとHash値を列挙して演算してたりするけど、全部ほしい場合はあまり思いつかなくて。。。

あっ、何のHashが取得可能かは、dirコマンドでこんなで。

>>> import hashlib
>>> print(dir(hashlib))
..., 'md5', ..., 'sha1', 'sha224', 'sha256', ...

所感を一言

まあまあ面白かった。
あと、参考になるURLがこれ。
あとできっちり試したいです。
巨大テキスト読み込みはほかでもあると思うので。

■Pythonで大きなファイルのMD5チェックサムをチェックする時にMemoryErrorを回避する
https://rcmdnk.com/blog/2015/07/18/computer-python/

1
1
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
1
1