读文件的正确方法及其背后机制

应该使用以下格式读文件:

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. 
The for line in f treats the file object f 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编辑  收藏  举报

导航