如何迭代父目录中的所有目录以获取所有文件的哈希值,然后后退一步遍历其余目录?

问题描述 投票:0回答:1

我正在用 Python 构建一个文件完整性监视器。我当前的挑战是弄清楚如何迭代用户选择的父目录中存在的所有目录,以验证存在的所有文件的哈希值,然后将哈希值保存到名为 benchmark.txt 的 txt 文件中。一旦一个目录被完全扫描并且当前子目录中没有更多的目录,我想自动返回一个目录并扫描下一个目录,然后再次执行此操作,直到该父目录下确实没有更多的目录为止所有文件均已扫描。这是我的代码:

def new_baseline():
    # Calculate hash from the target files and store in baseline.txt

    if os.path.exists(baseline):
        os.remove(baseline)
    # For each directory within the chosen directory
    # scan each file
    # then move onto the next directory and scan each file there until there are no more deeper directories
    for subdir, dirs, files in os.walk(directory):
        for filename in files:
            filehash = hashlib.sha256()
            fn = os.path.join(directory, filename)
            with open(fn, 'rb') as f:
                while True:
                    data = f.read()
                    if not data:
                        break
                    if data:
                        filehash.update(data)
                f.close()
            f = open(baseline, 'a')
            print(f"{fn} | {filehash.hexdigest()}", file=f) # Sends the print output to the baseline file
            print(f"{fn} | {filehash.hexdigest()}")

            f.close()

directory是用户在main函数中选择的目录。如果我只扫描一个目录,则此功能有效,但是请参阅我上面的问题。我如何遍历目录中的所有文件,然后再次向下,然后返回查看不同的目录?

这些是直接在我的文档目录下的目录,这是我要扫描的所选目录。

这是测试文件目录

这是 hp 目录

python iteration
1个回答
0
投票

您遇到的问题是构建文件的完整路径名。

os.walk
仅迭代父目录。它会生成当前正在查看的目录以及您将在其中找到的子目录和文件。使用
subdir
构建所包含文件的路径。

for subdir, dirs, files in os.walk(directory):
    for filename in files:
        filehash = hashlib.sha256()
        fn = os.path.join(directory, filename)
© www.soinside.com 2019 - 2024. All rights reserved.