zhangxaochen
zhangxaochen

Reputation: 34007

File opened in a function doesn't need to be closed manually?

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?

Upvotes: 0

Views: 138

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

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:

Upvotes: 1

Guy Gavriely
Guy Gavriely

Reputation: 11396

$ 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

Upvotes: 1

Brian Schlenker
Brian Schlenker

Reputation: 5426

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.

Upvotes: 3

Related Questions