栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号