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

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

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.
原文地址:https://www.cnblogs.com/freshair_cnblog/p/7991944.html