====== Python 读取文件的最后一行 ====== 在读取大文件的时候,有时只需要读取文件的最后一行,如果从头开始的读的话会浪费很多资源。 ===== 代码实现 ===== 下面的代码可以直接读取文件的最后一行: def get_last_line(inputfile) : filesize = os.path.getsize(inputfile) blocksize = 1024 dat_file = open(inputfile, 'rb') last_line = "" if filesize > blocksize : maxseekpoint = (filesize // blocksize) dat_file.seek((maxseekpoint-1)*blocksize) elif filesize : #maxseekpoint = blocksize % filesize dat_file.seek(0, 0) lines = dat_file.readlines() if lines : last_line = lines[-1].strip() #print "last line : ", last_line dat_file.close() return last_line ===== 参考 ===== * http://code.activestate.com/recipes/578095/