Python—如何打开文件并以字节为单位指定偏移量?

2024-04-29 08:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,它将定期解析一个Apache日志文件,记录它的访问者、带宽使用情况等。。

问题是,我不想打开日志并解析已经解析的数据。例如:

line1
line2
line3

如果我解析那个文件,我将保存所有行,然后保存偏移量。这样,当我再次解析它时,我得到:

line1
line2
line3 - The log will open from this point
line4
line5

第二轮,我要4号线和5号线。希望这有意义。。。

我需要知道的是,我如何才能做到这一点?Python有seek()函数来指定偏移量。。。那么,在解析日志之后,我是否只获取日志的文件大小(以字节为单位),然后在第二次记录日志时将其用作偏移量(以seek()为单位)?

我似乎想不出一种方法来编写此代码>;<


Tags: 文件the数据程序apache记录情况单位
3条回答
log = open('myfile.log')
pos = open('pos.dat','w')
print log.readline()
pos.write(str(f.tell())
log.close()
pos.close()

log = open('myfile.log')
pos = open('pos.dat')
log.seek(int(pos.readline()))
print log.readline()

当然,您不应该这样使用它-您应该将操作包装在诸如save_position(myfile)load_position(myfile)之类的函数中,但是功能是全部的。

由于file类的seektell方法,您可以管理文件中的位置。请参见 https://docs.python.org/2/tutorial/inputoutput.html

下次打开时,tell方法将告诉您在哪里查找

如果日志文件很容易放入内存中(这是一个合理的轮换策略),则可以很容易地执行以下操作:

log_lines = open('logfile','r').readlines()
last_line = get_last_lineprocessed() #From some persistent storage
last_line = parse_log(log_lines[last_line:])
store_last_lineprocessed(last_line)

如果你做不到这一点,你可以使用类似的方法(请参阅公认答案中的seek and tell,以防你需要使用它们)Get last n lines of a file with Python, similar to tail

相关问题 更多 >