处理文件时,一个常见的需求就是读取文件的最后一行。那么这个需求用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. 注意边界条件的处理,比如文件只有一行的情况。
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!