0

If I open a file in a function:

In [108]: def foo(fname):
     ...:     f=open(fname)
     ...:     print f
     ...:     

In [109]: foo('t.py')
<open file 't.py', mode 'r' at 0x05DA1B78>

Is it better to close f manually or not? Why?

tshepang
  • 12,111
  • 21
  • 91
  • 136
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108

3 Answers3

3

It is better to close the file when you are done with it because it is a good habit, but it isn't entirely necessary because the garbage collector will close the file for you. The reason you'd close it manually is to have more control. You don't know when the garbage collector will run.

But even better is to use the with statement introduced in python 2.5.

with open(f_name) as f:
    # do stuff with f
    # possibly throw an exception

This will close the file no matter what happens while in the scope of the with statement.

Brian Schlenker
  • 4,966
  • 6
  • 31
  • 44
1

Yes, it is better to close the file manually or even better use the with statement when dealing with files(it will automatically close the file for you even if an exception occurs). In CPython an unreferenced file object object will be closed automatically when the garbage collector actually destroys the file object, until then any unflushed data/resources may still hang around in memory.

From docs:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.


Related:

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1
$ cat /proc/sys/fs/file-max
390957

this may break my system ( forgive me for not trying :) ):

fs = []
for i in range(390957+1):
    fs.append(open(str(i), 'w'))
for f in files:
    f.close()

this (hopefully) won't:

for i in range(390957+1):
    with open(str(i), 'w') as f:
        # do stuff
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42