2017-03-04 1 views
-1

파일을 변경 한 경우 검사 : 사용자가 file.It에서 변경 한 경우 어떻게 확인하고있어이 있지만 작동파이썬 - 사용자가 난 그냥 몇 가지 코드를 작성했습니다

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 
내가 빨리 말대꾸 컴파일러를 작성해야

및 그 파일에 무언가를 추가 할 때만, 단어 나 숯을 삭제하면 발견되지 않습니다.

이유가 궁금하십니까?

+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

관련 문제