读文件的正确方法及其背后机制
应该使用以下格式读文件:
with open(...) as f:
for line in f:
<do something with line>
其理由如下:
The with
statement handles opening and closing the file, including if an exception is raised in the inner block.
Thefor line in f
treats the file objectf
as an iterable, which automatically uses buffered IO and memory management
so you don't have to worry about large files.
posted on 2017-12-06 11:46 freshair_cn 阅读(327) 评论(0) 编辑 收藏 举报