推荐使用 “with”语句 管理文件和类似的资源:
with open("hello.txt") as hello_file:
for line in hello_file:
print line
对于不支持 with
语句且类似文件的对象, 应该使用 contextlib.closing()
:
import contextlib
with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
for line in front_page:
print line