python 中的 Slurp 文件

Slurp file in python

要吞噬文件,我可以执行以下任一操作:

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

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

这里使用with语句有什么好处吗?

第一种方法确保无论如何都会关闭文件。就像在做:

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