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

How to grab all files in a folder and get their MD5 hash in python?

我正在尝试编写一些代码来获取文件夹中每个 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

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

我认为您最终只打开了一个空文件。这样做的原因是您获取 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)

glob.glob returns 文件列表。只需使用 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))