如何获取文件夹中的所有文件并在python中获取MD5哈希?

时间:2016-03-19 07:56:02

标签: python md5

我正在尝试编写一些代码来获取文件夹中每个exe文件的md5。

我的问题是我不明白该怎么做。仅当文件夹仅包含一个文件时,它才有效。这是我的代码:

import glob
import hashlib
file = glob.glob("/root/PycharmProjects/untitled1/*.exe")

newf = str (file)
newf2 =  newf.strip( '[]' )
newf3 = newf2.strip("''")

with open(newf3,'rb') as getmd5:
    data = getmd5.read()
    gethash= hashlib.md5(data).hexdigest()
    print gethash

我得到了结果:

a7f4518aae539254061e45424981e97c

我想知道如何对文件夹中的多个文件执行此操作。

2 个答案:

答案 0 :(得分:8)

glob.glob返回文件列表。只需使用for迭代列表:

import glob
import hashlib

filenames = glob.glob("/root/PycharmProjects/untitled1/*.exe")

for filename in filenames:
    with open(filename, 'rb') as inputfile:
        data = inputfile.read()
        print(filename, hashlib.md5(data).hexdigest())

请注意,如果您在该目录中碰巧有一个大文件,这可能会耗尽您的内存,因此它是better to read the file in smaller chunks(此处适用于1 MiB块):

def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(2 ** 20), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

for filename in filenames:
    print(filename, md5(filename))

答案 1 :(得分:1)

我想最后,你只打开一个空文件。原因是您获取glob返回的列表并删除其字符串表示中的列表标记(并且仅在使用strip时在字符串的两端。这给出了类似于:

file1.exe' 'file2.exe' 'file3.exe

然后你打开这个字符串,试图打开一个这样的文件。事实上,我甚至对其工作感到惊讶(除非你只有一个档案)!你应该得到FileNotFoundError

您要做的是迭代glob.glob返回的所有文件:

import glob
import hashlib
file = glob.glob("/root/PycharmProjects/untitled1/*.exe")

for f in file:
    with open(f, 'rb') as getmd5:
        data = getmd5.read()
        gethash = hashlib.md5(data).hexdigest()
        print("f: " + gethash)
相关问题