您的位置:首页 > 编程语言 > Python开发

python3.x输出文件最后几行

2016-05-13 21:02 417 查看

1.如果文件比较小可以这么做:

file = open('mytxt', 'r')
output = file.readlines[-n:]
print(output)<span style="white-space:pre">	</span>



2.如果文件较大,就要用到seek()了:


先看看seek的用法:
seek():移动文件读取指针到指定位置
tell():返回文件读取指针的位置
seek()的三种模式:
    
a:f.seek(p,0)  移动当文件第p个字节处,绝对位置


b:f.seek(p,1)  移动到相对于当前位置之后的p个字节


        c:f.seek(p,2)  移动到相对文章尾之后的p个字节


        d: f.seek(0)是移动到文件初始位置

所以,你可以这么做:
file = open('mytxt')
file.seek(p, 2)
for line in file:
print(line, end = ' ' )<span style="white-space:pre">	</span>

但是这会报错io.UnsupportedOperation: can't do nonzero end-relative seeks

后面查找原因,是因为file.seek(p, 2)只能在file= open('mytxt.txt', 'b')下使用,而中文被b以后就变成了乱码,不能接受

3.deque

最后看到了deque可以实现,具体用法是:
from collections import deque
file = open('mytxt.txt')
output= deque(file, n)
list1 = list(output)
for item in list1:
<span style="white-space:pre">	</span>print(item, end = ' ')


所以文件较大可以用这种方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: