Python - 检查用户是否更改了文件

2024-04-18 17:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚写了一些代码:

    hasher = hashlib.sha1()
    inputFile = open(inputPath, 'r')

    hasher.update(inputFile.read().encode('utf-8'))
    oldHash = hasher.hexdigest()
    newHash = ''

    while True:

        hasher.update(inputFile.read().encode('utf-8'))
        newHash = hasher.hexdigest()

        if newHash != oldHash:
            print('xd')

        oldHash = newHash

我需要快速编写sass编译器,并检查用户是否对文件。它工作,但只有当我添加一些东西到文件,当我删除任何字或字符,它不会检测到它。你知道吗

你知道为什么吗?你知道吗


Tags: 文件代码readupdateopensha1utfencode
1条回答
网友
1楼 · 发布于 2024-04-18 17:26:13

您可以使用^{}检查上次修改的时间,而不是立即检查哈希。你知道吗

考虑到:

in_path = "" # The sass/scss input file
out_path = "" # The css output file

然后检查文件是否已更改,只需执行以下操作:

if not os.path.exists(out_path) or os.path.getmtime(in_path) > os.path.getmtime(out_path):
    print("Modified")
else:
    print("Not Modified")

检查文件是否已修改后,可以检查哈希:

import hashlib

def hash_file(filename, block_size=2**20):
    md5 = hashlib.md5()
    with open(filename, "rb") as f:
        while True:
            data = f.read(block_size)
            if not data:
                break
            md5.update(data)
    return md5.digest()

if not os.path.exists(out_path) or hash_file(in_path) != hash_file(out_path):
    print("Modified")
else:
    print("Not Modified")

总的来说,您可以这样组合if语句:

if not os.path.exists(out_path) \
        or os.path.getmtime(in_path) > os.path.getmtime(out_path) \
        or hash_file(in_path) != hash_file(out_path):
    print("Modified")
else:
    print("Not Modified")

相关问题 更多 >