#!/usr/bin/env python# -*- coding: utf-8 -*-#tell () method returns the current position of the file, which is the current position of the file pointer. #使用with的目的是为里可以自动close掉文件对象 # Generator Simple small particle def foo1 (): yield 1 yield 2 yield 3 yield 4 for i in foo1 (): print (i) "If Executed: print ( Foo1 ()) Call this function, the return is a generator generator only to traverse the time of the function code will be executed, and each time the loop only executes a generator is a yield statement function execution Process Simple overview: 1, first execute the function, then traverse, traverse to the first bar, Execute yield 12, traverse to 2nd, do not go through the yield 1, but directly execute yield 23, and so on 4, characteristics: Will temporarily save the execution position "' #文件遍历小粒子 # Common function Implementation # Set a file to be read files = '/etc/passwd ' #普通函数def foo2 (): with open (Files, ' R ') as f: print (' filename: ', f.name) seek_id = 0 while true: &nbSp; f.seek (seek_id) data = f.readline () if data: #获取文件指针的当前位置 seek_id = f.tell () print (' file pointer current position: %d ' % (seek_id)) print (' read: %s ' % (data)) else: break# call this function directly Foo2 () #生成器实现def foo (): seek_id = 0 while true: with open (Files, ' R ') as f: F.seek (seek_id) data = F.readline () if data: seek_id = f.tell () print (' File pointer current position: %d ' % (seek_id)) yield data else: break# executes the code inside the function by traversing the generator FOR VAL&NBSp;in foo (): print (Val)
This article is from the "Fa&it-Q Group: 223843163" blog, please be sure to keep this source http://freshair.blog.51cto.com/8272891/1870539
Python's more memory-saving way to read files