美文网首页
迭代器 和 with 处理读取文件

迭代器 和 with 处理读取文件

作者: lmem | 来源:发表于2016-12-13 18:52 被阅读23次

1.迭代器

class Fib:
    '''生成菲波拉稀数列的迭代器'''
    def __init__(self, max):
        self.max = max
    def __iter__(self):
        self.a = 0
        self.b = 1
        return self
    def __next__(self):
        fib = self.a
        if fib > self.max:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        return fib

==> iter() 方法能返回任何实现了 next() 方法的对象。 在本例(甚至大多数例子)中,
iter() 仅简单返回 self , 因为该类实现了自己的
next() 方法。
==>当 next() 方法抛出 StopIteration 异常, 这是给调用者表示迭代用完了的信号。
==》 for 循环调用 iter(fib_inst) , 它返回迭代器
==》 for 循环调用 next(fib_iter) , 它又调用 fib_iter 对象的 next() 方法,产生下一个菲波拉稀计算并返回值

使用

for n in Fib(1000):
...     print(n, end=' ')

一个读取遍历文件的例子

class LazyRules:
    rules_filename = 'plural6‐rules.txt'
    def __init__(self):
        self.pattern_file = open(self.rules_filename,encoding='utf‐8')
        self.cache = []
    def __iter__(self):
        self.cache_index = 0
        return self
    def __next__(self):
        self.cache_index += 1
        if len(self.cache) >= self.cache_index:
            return self.cache[self.cache_index ‐ 1]
        if self.pattern_file.closed:
            raise StopIteration
        line = self.pattern_file.readline()
        if not line:#文件结尾了
            self.pattern_file.close()
            raise StopIteration
        pattern, search, replace = line.split(None, 3)
        funcs = build_match_and_apply_functions(
            pattern, search, replace)
        self.cache.append(funcs)
        return funcs
rules = LazyRules()

问题:
==》文件长时间打开,应该使用seek() 方法重新定位

2.文件读取

一行行读取,注意encoding必须指定,否则可能会报错

with open('examples/favorite‐people.txt', encoding='utf‐8') as a_file: 
    for a_line in a_file:                                               
        line_number += 1 
        print('{:>4} {}'.format(line_number, a_line.rstrip()))

追加写

with open('test.log', mode='a', encoding='utf‐8') as a_file:  ③
     a_file.write('and again') 

二进制文件的读取

an_image = open('examples/beauregard.jpg', mode='rb')  

重定向

import sys 
  class RedirectStdoutTo: 
    def __init__(self, out_new):         
           self.out_new = out_new 
 
    def __enter__(self): 
        self.out_old = sys.stdout
            sys.stdout = self.out_new   
    def __exit__(self, *args): 
        sys.stdout = self.out_old   

print('A')  
with open('out.log', mode='w', encoding='utf‐8') as  a_file, RedirectStdoutTo(a_file): 
    print('B')  
print('C') 

..................
you@localhost:~/diveintopython3/examples$ python3  stdout.py 
A 
C  
you@localhost:~/diveintopython3/examples$ cat out.log  B 

相关文章

网友评论

      本文标题:迭代器 和 with 处理读取文件

      本文链接:https://www.haomeiwen.com/subject/acebmttx.html