python 高效读取文件

来源:互联网 发布:linux进去文件夹 编辑:程序博客网 时间:2024/06/08 06:26

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 eachlineif __name__ == '__main__':    filename = './file.py'    read_file(filename)    print 'with read'    with_file(filename)


0 0
原创粉丝点击