Python recipe(10):逐段处理文件
2010-05-22 22:48
453 查看
代码何在?
Example Source Code [http://www.cnblogs.com/tomsheep/]
以上代码改写自Python Cookbook 4-9
概述:
逐段处理文件。自定义Paragraphs类,实现容器行为函数__getitem__
代码说明:
1.__getitem__函数可以使自定义类型具有容器行为,x[key]访问
2.在编写代码时,一开始在tag1处没有使用try…except,但是奇怪的是代码运行时并没有抛出IndexError,而是少打出一个para,想了一阵,觉得应该是在__getitem__外层捕捉了IndexError,自己尝试了一下,在__getitem__中手动raise IndexError,果然没有抛出(而ValueError就会抛出)可见__getitem__机制调用外层捕获了IndexError
Example Source Code [http://www.cnblogs.com/tomsheep/]
''' Created on 2010-5-22 @author: lk ''' class Paragraphs: def __init__(self, fileobj, seperator = '\n'): self.seq = fileobj.readlines() self.line_num = 0 self.para_num = 0 if seperator[-1:]!='\n':seperator += '\n' self.seperator = seperator def __getitem__(self, index): if index != self.para_num: raise TypeError, 'only sequential access supported' #get the first line of current paragraph self.para_num += 1 while 1: line = self.seq[self.line_num] self.line_num += 1 if line != self.seperator: break result = [line] #get the rest while 1: # line = self.seq[self.line_num] #tag1:
try: line = self.seq[self.line_num] except IndexError: break self.line_num += 1 if line == self.seperator: break result.append(line) return ''.join(result) if __name__ == '__main__': text = Paragraphs(open("test.txt")) for para in text: print para
以上代码改写自Python Cookbook 4-9
概述:
逐段处理文件。自定义Paragraphs类,实现容器行为函数__getitem__
代码说明:
1.__getitem__函数可以使自定义类型具有容器行为,x[key]访问
2.在编写代码时,一开始在tag1处没有使用try…except,但是奇怪的是代码运行时并没有抛出IndexError,而是少打出一个para,想了一阵,觉得应该是在__getitem__外层捕捉了IndexError,自己尝试了一下,在__getitem__中手动raise IndexError,果然没有抛出(而ValueError就会抛出)可见__getitem__机制调用外层捕获了IndexError
相关文章推荐
- python 学习笔记(10)重构与文件处理
- Python recipe(9): 文件的逐词处理
- Python CSV文件处理/读写及With as 用法
- Python处理大文件
- python文件中字符串处理的脚本示例
- Python-Selenium2做Web自动化测试(10)-浏览器多窗口处理、alert/confirm/prompt 处理
- 《python》学习笔记(Day2),读入磁盘文件,经过处理,保存成相应的磁盘文件
- [原]Python 简单文件处理
- python爬去内涵段子(json文件处理)
- Python open()文件处理使用介绍
- python处理某些文件夹下的csv文件,提取指定行到新文件中
- python脚本处理文件
- 使用python处理文件
- Python脚本10 —— 复制json文件并替换指定字段
- java与python在处理大文件操作上的对比
- 使用python处理中文csv文件,并让excel正确显示中文(避免乱码)
- python IO文件处理
- Python遍历文件夹 处理json文件
- Python文件处理
- python基础===open()文件处理使用介绍