4

My requirement is to checks to see if a file has changed since the last run. I have made an attempt to do with this os.stat and I'm not sure whether it is a correct way or not.

import os
import json

file_info = os.stat("cli.py")
with open("log.txt", "r") as file:
    line = json.loads(file.readline())
    if list(set(line)-set(list(file_info))):
       print("Changes in file")
       with open ("log.txt", "w+") as f:
           f.write(str(list(file_info)))

I looking for is there any better ideas or am I doing it in correct way or not. Any help is appreciated

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
  • are you comparing the full file content line for line? why not comparing checksums, e.g md5 – mzoll Apr 04 '18 at 10:56
  • Have u seen this link https://stackoverflow.com/q/182197/7636315 .. It talks abt variety of methods for this purpose like polling (performance concerns), QfileSystemWatcher (depends on pyqt), Watchdog (python api library) etc. This should help u i think. – Paandittya Apr 04 '18 at 10:58
  • @MarcelZoll No I'am comparing the file info like modified date, inod no with the info stored in a file when last runs, Its not the file contents. I don't have any idea about checksums or md5 . – Vikas Periyadath Apr 04 '18 at 11:07

1 Answers1

2

You can use a checksum, e.g. MD5

import hashlib

with open("yourfile", "rb") as f:

    print(hashlib.md5(f.read()).hexdigest())

https://docs.python.org/3/library/hashlib.html

If you need to know where the file has changed use difflib, shipped with Python. For links to examples see comments.

Joe
  • 6,758
  • 2
  • 26
  • 47
  • So does it show the changes in file since last run of this script ? – Vikas Periyadath Apr 05 '18 at 04:43
  • This only shows if the file has changed not where. To see where it changed use the difflib, also shipped with Python. https://docs.python.org/3.5/library/difflib.html – Joe Apr 05 '18 at 08:35
  • There are many examples around, e.g. https://www.smallsurething.com/comparing-files-in-python-using-difflib/ or https://stackoverflow.com/questions/977491/comparing-two-txt-files-using-difflib-in-python – Joe Apr 05 '18 at 08:36
  • So how does this tell us the file has changed? When the checksum changes? – CrazyVideoGamer Jun 20 '23 at 02:40