您的位置:首页 > 其它

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

2017-12-06 11:46 232 查看
应该使用以下格式读文件:
with open(...) as f:
for line in f:
<do something with line>
其理由如下:
The [code]with
statement handles opening and closing the file, including if an exception is raised in the inner block. [/code]
The [code]for line in f
treats the file object
f
as an iterable, which automatically uses buffered IO and memory management[/code]
so you don't have to worry about large files.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: