python - 在两次打印输出中检查文本文件更新结果

标签 python

我有一个不断更新的文本文件 foo.txt。我只想在文件更新时阅读 foo.txt 的最后一行。我有一个 while 循环不断打开文件并检查它。在循环内,我有一些代码打印文件的最后一行,然后将其存储在 lastmsg.txt 中。在下一次迭代中,它检查文件的最后一行是否不等于 lastmsg.txt 中存储的内容。如果两个值不相等(文件已更新并添加了新行),它将打印文件中的最后一条消息。这是代码

import time
while True:
    fileHandle = open ("foo.txt","r" )
    lineList = fileHandle.readlines()
    fileHandle.close()
    msg = lineList[len(lineList)-1]
    if(open("lastmsg.txt", "r").read() != msg):
        f = open("lastmsg.txt", "w")
        f.write(msg)
        print(msg)
    time.sleep(0.5)

这似乎可行,但是,它会打印两次 msg。所以如果abc被修改为文件,输出将是

abc
abc

最佳答案

我添加了 f.close() 行,之后,它只打印一次 msg。

import time
while True:
    fileHandle = open ("foo.txt","r" )
    lineList = fileHandle.readlines()
    fileHandle.close()
    msg = lineList[-1]
    if(open("lastmsg.txt", "r").read() != msg):
        f = open("lastmsg.txt", "w")
        f.write(msg)
        f.close()  # <---- new line
        print(msg)
    time.sleep(0.5)

关于python - 在两次打印输出中检查文本文件更新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58487434/

相关文章:

python - 在 OpenCV2 中找到最接近图像中心的轮廓

python - Python 描述符中实例和所有者的用途是什么?

python - 用于匹配重复出现的模式的正则表达式

python c api创建一个python模块

python 3 : unsupported operand type(s) for +: 'float' and 'str'

python - 如何将 nameko 依赖项传递给 SqlAlchemy 事件处理程序?

python - Pandas N 元语法到列

Python 项目结构 : "Unresolved reference"

python - 无法使用 Tkinter 条目小部件按住用户通过函数输入的键

python - 使用 Nginx 和 gunicorn : permission denied when connecting to webpage. socks 的服务 flask 应用程序