程序找错题:下面的代码哪里有错?
f = open('/Users/michael/test.txt', 'r')
for line in f.readlines():
print(line.strip())
f.close()
答:
open 文件后,读取文件过程中可能会有IOError,这样会导致程序终止,无法执行close文件对象,造成内存占用,可以加上try finally,但这样的代码明显不pythonic,可以使用with关键字。
with open('/Users/michael/test.txt', 'r') as f:
for line in f.readlines():
print(line.strip())
关于with语句更多详解:
https://blog.csdn.net/wusuopubupt/article/details/29369601
Python文件读写,用with open语句:
https://www.cnblogs.com/ymjyqsx/p/6554817.html
浅谈Python的with语句【上下文管理器】