我正在尝试重复读取一个系统日志,并且只从我上次读取的那一点开始。我试图保存tell()的位置是一个sperate文件,并在每次读取之前重新加载以进行搜索。
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()
答案 0 :(得分:3)
撰写str(last_loc)
代替last_loc
。
其余的可能是可选的。
w
代替w+
来撰写位置。/var/log/messages
。with
自动关闭文件。strip
。read
上使用readline
代替lf
。您可以为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))
答案 1 :(得分:0)
你的readline很奇怪。你要做的是:
1)将值保存为字符串并解析它:
lf.write(str(last_loc))
2)保存并重新读取位置为int:
lf.write(struct.pack("Q",lf.tell()))
last_pos = struct.unpack("Q",lf.read())