# -*- coding: cp936 -*-
import os,sys,re
def lastline():
global pos
while True:
pos = pos - 1
try:
f.seek(pos, 2) #从文件末尾开始读
if f.read(1) == '\n':
break
except: #到达文件第一行,直接读取,退出
f.seek(0, 0)
print f.readline().strip()
return
print f.readline().strip()
if __name__ == "__main__":
f = open('1.txt','rb') #‘r’的话会有两个\n\n
pos = 0
for line in range(2):#需要倒数多少行就循环多少次
lastline()
f.close()
# -*- coding: cp936 -*-
import os,sys,re
def lastline():
global pos
while True:
pos = pos - 1
try:
f.seek(pos, 2) #从文件末尾开始读
if f.read(1) == '\n':
该博客介绍了如何使用Python读取文件的末尾N行。通过全局变量pos调整文件指针,从文件尾部开始向前查找,直到找到换行符为止,从而实现读取指定数量的文件末尾行。
最低0.47元/天 解锁文章
4230

被折叠的 条评论
为什么被折叠?



