2017-03-04 96 views
-1

我刚写了一些代码: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编译器和如何我检查,如果用户在用户file.It任何改变的作品,但只有当我添加一些文件,当我删除任何字或字符它不检测它。

你知道为什么吗?

+0

请花费一些时间创建一个[mcve] – Idos

+0

您不能'read()'同一个文件两次。你必须重新打开它。 –

回答

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") 
+0

非常感谢,这真的很有用:) –

+0

@KacperCzyż不客气!如果它帮助解决你的问题,那么随时接受答案:) – Vallentin