I am using Python 3 and I would like to know how to continuously print the contents of a file every time it's updated. So, I do not want to nonstop print the contents over and over, I just want to print when the file is updated.
How can I do this?
CodePudding user response:
from pathlib import Path
import time
file = Path('myfile')
# print the current content
old_time = file.stat().st_mtime
print(file.read_text())
while True:
# every second (time.sleep(1)) check if the modification time of the file has changed. If so, print the content of the file
if file.stat().st_mtime != old_time:
old_time = file.stat().st_mtime
print(file.read_text())
time.sleep(1)