如何从上次位置反复读取文件
我正在尝试反复读取一个系统日志(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
把
last_loc
改成str(last_loc)
。其他的可能都是可选的。
- 写入位置时用
w
,不要用w+
。 - 用完
/var/log/messages
后记得关闭它。 - 根据你使用的Python版本(肯定是2.6或更新的版本,可能2.5也可以),你可以用
with
来自动关闭文件。 - 如果你只是写值,可能不需要用
strip
。 - 在
lf
上可以直接用read
,不用readline
。 你可以直接遍历文件,而不是用
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))