2

To slurp a file I can do either:

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

or

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

Is there any advantages to use the with statement here?

nowox
  • 25,978
  • 39
  • 143
  • 293

1 Answers1

3

The first method ensures that the file will be closed no matter what. It's like doing:

try:
    fd = open('foo')
    content = fd.read()
    # ... do stuff here
finally:
    fd.close()
alexpeits
  • 847
  • 8
  • 18
  • 1
    Isn't also the case with the latter solution? Once the file is read the gc will automatically close the file pointer right? – nowox Dec 01 '16 at 10:40
  • 3
    I will leave the explanation to [this](http://stackoverflow.com/a/7396043/5762711) answer, which does it beutifully :) – alexpeits Dec 01 '16 at 10:45