更新时打印文件内容

Print Contents of File When Updated

我正在使用 Python 3,我想知道如何在文件每次更新时连续打印文件的内容。所以,我不想一遍又一遍不停地打印内容,我只想在文件更新时打印。

我该怎么做?

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)