Python 如何从最后一个位置重复读取文件
我试图反复读取系统日志,并且只从上次读取时停止的点开始。我试图保存tell()的位置,它是一个高速文件,每次读取之前都要重新加载以查找Python 如何从最后一个位置重复读取文件,python,file,file-io,Python,File,File Io,我试图反复读取系统日志,并且只从上次读取时停止的点开始。我试图保存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 i
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()
str(last\u loc)
而不是last\u loc
其余的可能是可选的w
而不是w+
来写入位置/var/log/messages
与
一起使用来自动关闭文件strip
lf
上使用read
而不是readline
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))
你的阅读线很奇怪。您需要做的是: 1) 将值另存为字符串并对其进行分析:
lf.write(str(last_loc))
2) 将位置保存为int并重新读取:
lf.write(struct.pack("Q",lf.tell()))
last_pos = struct.unpack("Q",lf.read())
仍然没有告诉他如何将int写入文件:)
try:with open(“location.file”)为lf:s=lf.read()last\u pos=int(s),除了:last\u pos=0代码>你必须在评论中使用反勾号,但除此之外,这是一个很好的建议。