Home > Mobile >  Detecting changes in a txt file
Detecting changes in a txt file

Time:12-01

I am a beginner python programmer and I am wondering if there is any way to detect a change in a txt file on windows. Any suggestion is appreciated.

CodePudding user response:

There are many ways to go with it :

  • You can for example check the last modification date of the file every few seconds with os.path.getmtime(path), when the date change you know the file was edited.

  • You can also use some form of checksum (generate md5 hash of a file) on the file and check every few seconds if the checksum change (can get slow on big files since the checksum require to read the entire file)

  • You can also listen for signals send by windows directly and execute an event handler when you get a signal, this is harder to implement but by far the cleanest way to do it. (Edit, this seems to be what @martin kamau suggest in his answer)

  • Probably many more way that I can't think of right now...

CodePudding user response:

To watch for file changes in a file,

A python script found at https://luvocorp.co.ke/topic/watch-for-file-changes/ can be used.

import time import fcntl import os import signal

filename = "nameofthefile"

def handler(signum, frame): print "File %s modified" % (FNAME,)

....

  • Related