Sunday, July 3, 2016

python script to watch up for a file modification

python,script,file modification,useful
welcome to my first python tutorial in this blog
sometimes you would have to know if some import file has been modified so that you can prevent some damage to happen early so in this tuto you will learn how to use python to alert you if a specific file has been modified.
let's start

first we are going to import os and time modules

import os,time

now we are going to ask the user for the path of the specific file

file_path=input("insert the file path")

now we get the size of the file and back_up it to use it later in a while loop

size=os.path.getsize(file_path)
backup_size=size

now we will use a while loop and we will compare the size of file that we actualize every specific
amount of seconds (in this case 2) using time.sleep() function, and print that the file is ok in the actual time using the time.asctime() function.

while size==backup_size:
t=time.asctime()
print("the file is OK at : ",t)
time.sleep(2)

when the while loop breaks, that mean when the size the size is different than backup_size
we print that the file was modified and the time of modification

print("the file was modified at : ",time.asctime())


the final useful script is :

import os,time
file_path=input("insert the file path")
size=os.path.getsize(file_path)
backup_size=size
while size==backup_size:
t=time.asctime()
print("the file is OK at : ",t)
time.sleep(2)
print("the file was modified at : ",time.asctime())

i hope that you find this script useful and that you learned something new from this post
if you didn't understand something you can comment  right down
share it

0 comments:

Post a Comment