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

时间:2017-03-04 09:56:43

标签: 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编译器以及我如何检查用户是否对文件进行了任何更改。它有效但只有当我向文件添加内容时,当我删除任何单词或字符时它不会检测它。

你知道为什么吗?

1 个答案:

答案 0 :(得分:0)

您可以使用os.path.getmtime(path)检查上次修改时间,而不是立即检查哈希值。

考虑到:

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")
相关问题