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 = ' ')
所以文件较大可以用这种方法。
相关文章推荐
- pip install jupyter UnicodeDecodeError | ipython notebook 安装失败
- Python――How to use python pip/pur
- 如何上传python
- 如何上传python
- 最全Python爬虫总结
- Beautiful Soup 4库--python2.x(学习日记)
- Python实现欧拉计划23题
- Python之路—Day1
- 如何优雅的用Python玩转语音聊天机器人
- leetcode(8),Majority Element(python)
- python的import详解
- python的import详解
- python内置函数第四讲(2)
- python - num1 -初识python
- python的socket编程之udp编程
- python的socket编程之udp编程
- python的socket编程之udp编程
- python 学习笔记12(序列常用方法总结)
- PIL处理图片之加水印
- python监听本地目录,并将目录下的文件同步到远端服务器