python中的Slurp文件

时间:2016-12-01 10:34:51

标签: python file with-statement

要抓住文件,我可以这样做:

with open('foo', 'r') as fd:
   content = fd.read()

content = open('foo').read()

在这里使用with声明有什么好处吗?

1 个答案:

答案 0 :(得分:1)

第一种方法确保文件将被关闭,无论如何。它就像在做:

try:
    fd = open('foo')
    content = fd.read()
    # ... do stuff here
finally:
    fd.close()
相关问题