读文件的正确方法及其背后机制
应该使用以下格式读文件:
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 ftreats the file objectfas 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 阅读(334) 评论(0) 收藏 举报
浙公网安备 33010602011771号