这里会显示出您选择的修订版和当前版本之间的差别。
— |
python-files:last-line [2013/02/16 09:11] (当前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== Python 读取文件的最后一行 ====== | ||
+ | |||
+ | 在读取大文件的时候,有时只需要读取文件的最后一行,如果从头开始的读的话会浪费很多资源。 | ||
+ | |||
+ | ===== 代码实现 ===== | ||
+ | |||
+ | 下面的代码可以直接读取文件的最后一行: | ||
+ | |||
+ | <code 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 | ||
+ | </code> | ||
+ | |||
+ | ===== 参考 ===== | ||
+ | * http://code.activestate.com/recipes/578095/ | ||