【问题标题】:How to repeatedly read a file from the last location如何从最后一个位置重复读取文件
【发布时间】:2011-08-14 05:17:57
【问题描述】:

我正在尝试重复读取系统日志,并且只从我上次阅读的中断点开始。我正在尝试保存 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()

【问题讨论】:

    标签: python file file-io


    【解决方案1】:
    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. 您可以遍历文件本身,而不是使用 readlines 来代替 sl

      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))
      

    【讨论】:

    • try: with open("location.file") as lf: s = lf.read() last_pos = int(s) except: last_pos = 0;
    • 你必须在 cmets 中使用反引号,否则,很好的建议。
    【解决方案2】:

    你的阅读线很奇怪。您需要做的是:

    1) 将值保存为字符串并解析:

    lf.write(str(last_loc))
    

    2) 将位置保存并重新读取为 int:

    lf.write(struct.pack("Q",lf.tell()))
    last_pos = struct.unpack("Q",lf.read())
    

    【讨论】:

    • 仍然没有向他展示如何将 int 实际写入文件:)
    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2013-08-17
    • 2010-09-06
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多