python 读取文件头_python头,尾和向后读取文本文件的行

这是一个自定义的File类,用于帮助读取文件。它提供了head方法来获取文件的前几行,tail方法获取文件的末尾几行,以及backward方法实现倒序遍历文件内容。通过实例化此类并调用相应方法,可以方便地操作文件。
摘要由CSDN通过智能技术生成

这是我的个人文件类;-)

class File(file):

""" An helper class for file reading """

def __init__(self, *args, **kwargs):

super(File, self).__init__(*args, **kwargs)

self.BLOCKSIZE = 4096

def head(self, lines_2find=1):

self.seek(0) #Rewind file

return [super(File, self).next() for x in xrange(lines_2find)]

def tail(self, lines_2find=1):

self.seek(0, 2) #Go to end of file

bytes_in_file = self.tell()

lines_found, total_bytes_scanned = 0, 0

while (lines_2find + 1 > lines_found and

bytes_in_file > total_bytes_scanned):

byte_block = min(

self.BLOCKSIZE,

bytes_in_file - total_bytes_scanned)

self.seek( -(byte_block + total_bytes_scanned), 2)

total_bytes_scanned += byte_block

lines_found += self.read(self.BLOCKSIZE).count('\n')

self.seek(-total_bytes_scanned, 2)

line_list = list(self.readlines())

return line_list[-lines_2find:]

def backward(self):

self.seek(0, 2) #Go to end of file

blocksize = self.BLOCKSIZE

last_row = ''

while self.tell() != 0:

try:

self.seek(-blocksize, 1)

except IOError:

blocksize = self.tell()

self.seek(-blocksize, 1)

block = self.read(blocksize)

self.seek(-blocksize, 1)

rows = block.split('\n')

rows[-1] = rows[-1] + last_row

while rows:

last_row = rows.pop(-1)

if rows and last_row:

yield last_row

yield last_row用法示例:

with File('file.name') as f:

print f.head(5)

print f.tail(5)

for row in f.backward():

print row

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值