python怎么读文件最后几行

645次阅读
没有评论

python怎么读文件最后几行

处理文件时,一个常见的需求就是读取文件的最后一行。那么这个需求用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. 注意边界条件的处理,比如文件只有一行的情况。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-11-26发表,共计1559字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)