T
T
Do I need to close the file in this case? Why or why not?
for line in file('foo', 'r'):
print line
for line in file('foo', 'r'):
print line
Do I need to close the file in this case? Why or why not?
for line in file('foo', 'r'):
print line
T said:Do I need to close the file in this case? Why or why not?
for line in file('foo', 'r'):
print line
Do I need to close the file in this case? Why or why not?
for line in file('foo', 'r'):
print line
T said:Do I need to close the file in this case? Why or why not?
for line in file('foo', 'r'):
print line
T said:Do I need to close the file in this case? Why or why not?
for line in file('foo', 'r'):
print line
T enlightened us with:
Nope, it'll get closed automatically when the file object gets garbage
collected.
Thomas said:Are you asking if you can get away without closing it?
Or are you asking if it is a good idea to not close it?
Good programming practice says that if you open it - you close it.
And stay out of trouble ;-)
Thomas Bartkus
How do I close the file in the above case?
T said:How do I close the file in the above case?
f = open('foo', 'r')
try:
for line in f:
print line
finally:
f.close()
Though of course we have to remember that not all Python implementationsT> Do I need to close the file in this case? Why or why not?
T> for line in file('foo', 'r'):
T> print line
No. The magic of reference counting.
Though of course we have to remember that not all Python implementationsT> Do I need to close the file in this case? Why or why not?
T> for line in file('foo', 'r'):
T> print line
No. The magic of reference counting.
I was running a program in IDLE that opened a file for
reading and forgot to add the close.
The program ran and terminated normally.
But when I tried to open it from Windows Explorer,
I got the message that it was still in use. Had to close
IDLE to release it. That wouldn't have happened if I had
closed it from within the program.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.