[Python]如何取出一个超大文本文件的最后几行
来源:互联网 发布:网络图片头像带字图片 编辑:程序博客网 时间:2024/04/24 05:16
这是 python-中国 邮件列表中的一个问题。如果不考虑效率问题,这个问题可能很简单,直接read出整个文件的内容,然后split一下或者还有更简单的办法。但是如果这个文件是“超大”,那么为了区区几行而读入整个文件有点‘“得不偿失“。下面是我的实现。刚学python不久,也许没有发挥出它的优点。
#last lines
#by Kevin Yuan
def last_lines(filename, lines = 1):
#print the last line(s) of a text file
"""
Argument filename is the name of the file to print.
Argument lines is the number of lines to print from last.
"""
block_size = 1024
block = ''
nl_count = 0
start = 0
fsock = file(filename, 'rU')
try:
#seek to end
fsock.seek(0, 2)
#get seek position
curpos = fsock.tell()
while(curpos > 0): #while not BOF
#seek ahead block_size+the length of last read block
curpos -= (block_size + len(block));
if curpos < 0: curpos = 0
fsock.seek(curpos)
#read to end
block = fsock.read()
nl_count = block.count('/n')
#if read enough(more)
if nl_count >= lines: break
#get the exact start position
for n in range(nl_count-lines+1):
start = block.find('/n', start)+1
finally:
fsock.close()
#print it out
print block[start:]
if __name__ == '__main__':
import sys
last_lines(sys.argv[0], 5) #print the last 5 lines of THIS file
#last lines
#by Kevin Yuan
def last_lines(filename, lines = 1):
#print the last line(s) of a text file
"""
Argument filename is the name of the file to print.
Argument lines is the number of lines to print from last.
"""
block_size = 1024
block = ''
nl_count = 0
start = 0
fsock = file(filename, 'rU')
try:
#seek to end
fsock.seek(0, 2)
#get seek position
curpos = fsock.tell()
while(curpos > 0): #while not BOF
#seek ahead block_size+the length of last read block
curpos -= (block_size + len(block));
if curpos < 0: curpos = 0
fsock.seek(curpos)
#read to end
block = fsock.read()
nl_count = block.count('/n')
#if read enough(more)
if nl_count >= lines: break
#get the exact start position
for n in range(nl_count-lines+1):
start = block.find('/n', start)+1
finally:
fsock.close()
#print it out
print block[start:]
if __name__ == '__main__':
import sys
last_lines(sys.argv[0], 5) #print the last 5 lines of THIS file
- [Python]如何取出一个超大文本文件的最后几行
- PHP读取超大文件的最后几行
- 输出文件的最后几行,可以对付超大文件
- php读取超大文件最后几行
- 如何读取超大文本文件
- 根据最后一个逗号的索引,取出最后一个字符串
- 取出字符串的最后一个字符
- 读取一个文本文件的最后一行
- python删除文本文件中最后一个换行符
- php中如何获取文本文件并删除最后一个字符。
- 如何取出一个整数的每位数字
- C#读取超大文本文件的部分内容
- 解析出一个接口的数据,我要如何取出只有job_city=上海的几条数据呢
- 解析出一个接口的数据,我要如何取出只有job_city=上海的几条数据呢
- 从数据库表中取出最后插入的几条数据的SQL语句。
- 数据量超大的情况下如何添加一个字段
- 【笔试】超大文件里的数据去重排序;将log中MAC地址提取出来;取出数据库表T里第20行到29行的数据;如何判断一个二叉树B是不是二叉树A的子树?
- Linux如何通过命令查看日志文件的某几行(中间几行或最后几行)
- 可实现JSCROLLPANE内VIEW最大化的工具 - SWING组件
- 2005给编辑留下最深印象的十大热点事件
- 信息统计面板 - SWING组件
- 利用GDI+生成字体的无锯齿显示
- 学C#不学Java的最正当理由
- [Python]如何取出一个超大文本文件的最后几行
- WebLogic Server (UNIX/LINUX平台)简明安装手册
- 字符集涉及的问题
- 图象工具:可将SWING组件外观输出成图片的工具 - SWING组件
- 2005-12-29 工作日志
- 我不爱的女人却爱我那么深
- 全球500强的网站只有500个!强者生存!
- 当妻子被三个歹徒强奸后
- 时刻提醒自己的话 要每天看看的话(第一版)