gpt4 book ai didi

python - 如何从最后一个位置重复读取文件

转载 作者:行者123 更新时间:2023-11-28 16:51:19 24 4
gpt4 key购买 nike

我正在尝试反复阅读系统日志,并且只从我上次阅读的中断点开始。我正在尝试将 tell() 的位置保存为一个单独的文件,并在每次读取之前重新加载以进行查找。



lf = open("location.file", 'r')
s = lf.readline()
last_pos = int(s.strip())
lf.close()

sl = open("/var/log/messages", 'r')
sl.seek(last_pos)
for line in sl.readlines():
# This should be the starting point from the last read
last_loc = sl.tell()

lf = open("location.file", "w+")
lf.write(last_loc)
lf.close()

最佳答案

  1. str(last_loc) 而不是 last_loc

    其余的可能是可选的。

  2. 使用 w 而不是 w+ 来编写位置。
  3. 完成后关闭 /var/log/messages
  4. 根据您的 Python 版本(肯定是 2.6 或更新版本,可能是 2.5,具体取决于),您可能希望使用 with 自动关闭文件。
  5. 如果您只是写入值,则可能不需要 strip
  6. 您可以在 lf 上使用 read 而不是 readline
  7. 对于 sl,您可以遍历文件本身,而不是使用 readlines

    try:
    with open("location.file") as lf:
    s = lf.read()
    last_pos = int(s)
    except:
    last_post = 0

    with open("/var/log/messages") as sl:
    sl.seek(last_pos)
    for line in sl:
    # This should be the starting point from the last read
    last_loc = sl.tell()

    with open("location.file", "w") as lf:
    lf.write(str(last_loc))

关于python - 如何从最后一个位置重复读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7055170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com