如何从上次位置反复读取文件

3 投票
2 回答
781 浏览
提问于 2025-04-16 23:34

我正在尝试反复读取一个系统日志(syslog),并且每次都从上次读取的位置开始。我想把上次读取的位置保存到一个单独的文件里,然后在每次读取之前重新加载这个位置。



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


2 个回答

0

你的读取方式有点奇怪。你需要做的是:

1) 把值保存为字符串,然后再进行解析:

lf.write(str(last_loc))

2) 把值保存下来,然后再把它作为整数读取:

lf.write(struct.pack("Q",lf.tell()))
last_pos = struct.unpack("Q",lf.read())
3
  1. last_loc 改成 str(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))
    

撰写回答