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

dav*_*ave 15 python file-io byte offset

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

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

line1
line2
line3
Run Code Online (Sandbox Code Playgroud)

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

line1
line2
line3 - The log will open from this point
line4
line5
Run Code Online (Sandbox Code Playgroud)

第二轮,我会得到第4行和第5行.希望这是有道理的......

我需要知道的是,我该如何做到这一点?Python有seek()函数来指定偏移量...所以我只是在解析之后得到日志的文件大小(以字节为单位)然后在第二次记录它时使用它作为偏移量(在seek()中)?

我似乎无法想到一种编码方式>.<

luc*_*luc 14

您可以通过该类seektell方法管理文件中的位置,file请参阅 https://docs.python.org/2/tutorial/inputoutput.html

tell方法将告诉您下次打开时的搜索位置