【发布时间】:2019-04-26 13:53:18
【问题描述】:
我正在尝试读取 file.out 服务器文件,但我只需要读取日期时间范围内的最新数据。
是否可以使用带有模式(方法)的with open() 反向读取文件?
a+ 模式可以访问文件末尾:
``a+'' Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of the file,
irrespective of any intervening fseek(3) or similar.
有没有办法使用 a+ 或其他模式(方法)来访问文件末尾并读取特定范围?
由于常规r 模式从头开始读取文件
with open('file.out','r') as file:
已尝试使用reversed()
for line in reversed(list(open('file.out').readlines())):
但它没有为我返回任何行。
或者还有其他方法可以反向读取文件...帮助
编辑
到目前为止我得到了什么:
import os
import time
from datetime import datetime as dt
start_0 = dt.strptime('2019-01-27','%Y-%m-%d')
stop_0 = dt.strptime('2019-01-27','%Y-%m-%d')
start_1 = dt.strptime('09:34:11.057','%H:%M:%S.%f')
stop_1 = dt.strptime('09:59:43.534','%H:%M:%S.%f')
os.system("touch temp_file.txt")
process_start = time.clock()
count = 0
print("reading data...")
for line in reversed(list(open('file.out'))):
try:
th = dt.strptime(line.split()[0],'%Y-%m-%d')
tm = dt.strptime(line.split()[1],'%H:%M:%S.%f')
if (th == start_0) and (th <= stop_0):
if (tm > start_1) and (tm < stop_1):
count += 1
print("%d occurancies" % (count))
os.system("echo '"+line.rstrip()+"' >> temp_file.txt")
if (th == start_0) and (tm < start_1):
break
except KeyboardInterrupt:
print("\nLast line before interrupt:%s" % (str(line)))
break
except IndexError as err:
continue
except ValueError as err:
continue
process_finish = time.clock()
print("Done:" + str(process_finish - process_start) + " seconds.")
我添加了这些限制,因此当我找到行时,它至少可以打印出出现的事件,然后停止读取文件。
问题是它正在读取,但是速度太慢了..
编辑 2
(2019-04-29 9.34am)
我收到的所有答案都适用于反向阅读日志,但在我(也许对于其他人)的情况下,当你有 n GB 大小的日志时,下面 Rocky 的答案最适合我。
适合我的代码:
(我只在 Rocky 的代码中添加了 for 循环):
import collections
log_lines = collections.deque()
for line in open("file.out", "r"):
log_lines.appendleft(line)
if len(log_lines) > number_of_rows:
log_lines.pop()
log_lines = list(log_lines)
for line in log_lines:
print(str(line).split("\n"))
谢谢大家,所有答案都有效。
-lpkej
【问题讨论】:
-
你的最后一个
reversed()方法应该可以工作,尽管它的内存效率非常低(如果你的文件很大) -
如果您尝试使用
reversed没有返回数据,那是因为您调用readlines时文件为空(这不是必需的;list将遍历文件对象本身) . -
@RockyLi 是的,内存效率很低
标签: python file parsing logging