python可以通过迭代器和with语句高效低读取俄文件
如下:
</pre><pre name="code" class="python">#!/usr/bin/env python
def read_file(filename):
try:
fh = open(filename, 'r')
except IOError:
print 'open file error'
else:
for eachline in fh:
print eachline
finally:
fh.close()
def with_file(filename):
with open(filename, 'r') as f:
for eachline in f:
print eachline
if __name__ == '__main__':
filename = './file.py'
read_file(filename)
print 'with read'
with_file(filename)