导语:
本文主要介绍了关于python怎么读文件最后几行的相关知识,包括python读取文件某一行某个数,以及python每次n行读取文件这些编程知识,希望对大家有参考作用。
处理文件时,一个常见的需求是读取文件的最后一行。那么如何在python中实现这个需求呢?一个天真的想法如下:
with open('a.log', 'r') as fp:
lines = fp.readlines()
last_line = lines[-1]
即使没有异常处理,这段代码也不是完美的,因为如果文件很大,lines = fp.readlines() 会导致大量的时间和空间开销。
解决方法是定位文件指针指向文件末尾,然后从文件末尾探测一行的长度,读取最后一行。代码显示如下:
def __get_last_line(self, filename):
"""
get last line of a file
:param filename: file name
:return: last line or None for empty file
"""
try:
filesize = os.path.getsize(filename)
if filesize == 0:
return None
else:
with open(filename, 'rb') as fp: # to use seek from end, must use mode 'rb'
offset = -8 # initialize offset
while -offset < filesize: # offset cannot exceed file size
fp.seek(offset, 2) #read#offset chars from eof(represent by number'2')
lines = fp.readlines() # read from fp to eof
if len(lines) >= 2: # if contains at least 2 lines
return lines[-1] # then last line is totally included
else:
offset *= 2 # enlarge offset
fp.seek(0)
lines = fp.readlines()
return lines[-1]
except FileNotFoundError:
print(filename + ' not found!')
return None
其中有几个注意点:
1. fp.seek(offset[, where])中的where=0、1、2分别表示距文件头的偏移量、当前指针位置和文件尾。默认值为0,但如果要指定where=2,文件的打开方式必须是二进制打开,即使用'rb'模式,
2、设置偏移量时注意不要超过文件的总字节数,否则会报OSError。
3.注意边界条件的处理,比如文件只有一行的情况。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Python字符编码总结10/31
- ♥ python3格式输出有哪些方法?12/30
- ♥ ubuntu的python在哪里09/29
- ♥ 如何在python中实现异步非阻塞11/05
- ♥ python如何生成表单09/09
- ♥ python如何操作剪贴板?09/19
内容反馈