0

If I write code like this, What will happen? Will the file object close automatically?

# Do something before
# Make the value = 1 when the number in file.
for line in open('input_file.txt', 'r'):
    index_list[int(line)] = 1
# Do something later

Or I have to write code like this?

with open('xxx.txt', 'r') as f:
    # Do something
Deron Lee
  • 379
  • 1
  • 3
  • 8
  • 1
    1) No, it won't. 2) You should since using the `with` statement with `file` objects calls it's `.close` method for you behind the scenes (i.e automatically). – Dimitris Fasarakis Hilliard Mar 17 '17 at 15:01
  • @JimFasarakisHilliard In this first case as the file object doesn't have any references after the loop, hence it will get deallocated automatically and in turn calling [its close method](https://hg.python.org/cpython/file/2.7/Objects/fileobject.c#l612). Unless of course there's an exception, which is why `with` statement is always better. – Ashwini Chaudhary Mar 17 '17 at 15:39
  • @AshwiniChaudhary As far as I know, the language gaurantees no such thing, so it can vary wildly by implementation. And even in CPython, which does this, it depends a lot on when the object is actually garbage-collected, potentially leaving the file open longer than expected. So yeah, don't count on it... – marcelm Mar 17 '17 at 17:19

0 Answers0