应该使用以下格式读文件:
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.