python 倒读 一个文件,从最后一行往前读
2014-04-04 16:23
323 查看
#!/usr/bin/env python
# -*-mode: python; coding: iso-8859-1 -*-
#
# Copyright (c) Peter Astrand <astrand@cendio.se>
import os
import string
class BackwardsReader:
"""Read a file line by line, backwards"""
BLKSIZE = 4096
def readline(self):
while 1:
newline_pos = string.rfind(self.buf, "\n")
pos = self.file.tell()
if newline_pos != -1:
# Found a newline
line = self.buf[newline_pos+1:]
self.buf = self.buf[:newline_pos]
if pos != 0 or newline_pos != 0 or self.trailing_newline:
line += "\n"
return line
else:
if pos == 0:
# Start-of-file
return ""
else:
# Need to fill buffer
toread = min(self.BLKSIZE, pos)
self.file.seek(-toread, 1)
self.buf = self.file.read(toread) + self.buf
self.file.seek(-toread, 1)
if pos - toread == 0:
self.buf = "\n" + self.buf
def __init__(self, file):
self.file = file
self.buf = ""
self.file.seek(-1, 2)
self.trailing_newline = 0
lastchar = self.file.read(1)
if lastchar == "\n":
self.trailing_newline = 1
self.file.seek(-1, 2)
if __name__=="__main__":
br = BackwardsReader(open('txt.txt'))
for i in range(14):
print br.readline()
# -*-mode: python; coding: iso-8859-1 -*-
#
# Copyright (c) Peter Astrand <astrand@cendio.se>
import os
import string
class BackwardsReader:
"""Read a file line by line, backwards"""
BLKSIZE = 4096
def readline(self):
while 1:
newline_pos = string.rfind(self.buf, "\n")
pos = self.file.tell()
if newline_pos != -1:
# Found a newline
line = self.buf[newline_pos+1:]
self.buf = self.buf[:newline_pos]
if pos != 0 or newline_pos != 0 or self.trailing_newline:
line += "\n"
return line
else:
if pos == 0:
# Start-of-file
return ""
else:
# Need to fill buffer
toread = min(self.BLKSIZE, pos)
self.file.seek(-toread, 1)
self.buf = self.file.read(toread) + self.buf
self.file.seek(-toread, 1)
if pos - toread == 0:
self.buf = "\n" + self.buf
def __init__(self, file):
self.file = file
self.buf = ""
self.file.seek(-1, 2)
self.trailing_newline = 0
lastchar = self.file.read(1)
if lastchar == "\n":
self.trailing_newline = 1
self.file.seek(-1, 2)
if __name__=="__main__":
br = BackwardsReader(open('txt.txt'))
for i in range(14):
print br.readline()
相关文章推荐
- Python【读取文件,第一行与最后一行】
- Python:在文件中的每一行添加一个逗号
- Python 实现在文件中的每一行添加一个逗号
- Python读取文件的最后一行(非空行)
- Python:将一个文件中的每一行复制到一个新创建的文件中,并计算文件中总共有多少行
- python 读取文件,获取文件最后一行内容
- Python逐行读取文件,到最后一行结束
- Python遍历目录下所有文件的最后一行进行判断若错误及时邮件报警-案例
- python中读取txt文件,windows下么有毛病,到Linux下总是只有最后一行有效,怎么解决?
- python读取txt文件最后一行(文件大+文件小)
- python读取CSV文件以及“写入CSV致文件每一行后面会多一个空行”问题解决
- python读取txt文件最后一行(文件大+文件小)
- Python 实现在对一个目录下所有文件,指定某一行之后添加内容(批处理脚本)
- 文件操作之增删改查3---文件的修改,f.replace(),在linux里的一些应用sed,with语句方法来打开一个或多个文件避免忘记关闭,python一行写的太长,怎么编写多行的规范
- python 读取文件的最后一行
- python通过wxPython打开一个音频文件并播放的方法
- python 的重定向输出到一个文件
- python 统计一个目录中每个txt文件最重要的的词
- python 删除大文件中的某一行(最有效率的方法)