92

I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.

I didn't start using Python until 2.5 was out, so I'm used to the form:

with open('file.txt', 'r') as f:
    # do stuff with f

However, there is no with statement before 2.5, and I'm having trouble finding examples about the proper way to clean up a file object manually.

What's the best practice for disposing of file objects safely when using old versions of python?

Jon-Eric
  • 16,977
  • 9
  • 65
  • 97
TM.
  • 108,298
  • 33
  • 122
  • 127

4 Answers4

145

See docs.python.org:

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

Hence use close() elegantly with try/finally:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
    f.close()

This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().

Jon-Eric
  • 16,977
  • 9
  • 65
  • 97
  • Very simple, thanks. For some reason I was expecting that I'd need something more involved. – TM. Sep 22 '10 at 14:42
  • 17
    If `open` fails, an exception will be raised before the `try/finally` block is even entered. So `close` will not be called. (That's why you should call `open` before the `try`.) – FogleBird Sep 22 '10 at 14:44
  • 1
    @TM I added a note about `open` raising an exception. – Jon-Eric Sep 22 '10 at 14:48
  • 4
    This is what the with statement translates to behind the scenes. – Arlaharen Sep 22 '10 at 14:51
  • @Jon-Eric what if program was shut down when executing try blocks, would `f` be closed properly? – stanleyerror Feb 12 '15 at 07:06
  • @stanleyerror Yes `f` will be closed properly as long the shut down triggers a Python exception. (E.g., Ctrl-C) – Jon-Eric Feb 12 '15 at 16:59
  • @Jon-Eric I add a print next to the close function in finally block. However, I pressed Ctrl-C when executing try block, nothing is printed. Did I make a mistake? – stanleyerror Feb 12 '15 at 17:05
  • @stanleyerror I'd suggest asking that as a separate question where you can post the test code you're using and solicit answers from others. (I don't know the details of exactly how Python shuts down on various platforms.) – Jon-Eric Feb 12 '15 at 17:20
  • 1
    Opening the file should happen within the try. – Anthony Rutledge May 06 '17 at 01:42
  • @AnthonyRutledge If you do that, and close the file in the `finally` block, when an exception occurs while trying to open the file, the code in the `finally` block will still be executed. This means that another exception occurs since you try to close a file that was never opened, and may try to use a reference that hasn't been created. – Rik Schoonbeek Aug 05 '19 at 18:16
  • @RikSchoonbeek I have not been doing Python for a little while now, but my assumption at second glance here is that the `try` statement will not be reached if an exception is thrown by `open`. Context is key. – Anthony Rutledge Aug 06 '19 at 14:01
  • @RikSchoonbeek See my response below for the most robust solution, along the lines of AnthonyRutledge but without the issue you refer above. – mljrg Jun 25 '20 at 16:51
33

In the above solution, repeated here:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
   f.close()

if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:

f = None
try:
    f = open('file.txt', 'r')

    # do stuff with f

finally:
    if f is not None:
       f.close()
mljrg
  • 4,430
  • 2
  • 36
  • 49
  • Using a with open(...) statement, no matter how the with block is finished (even with an exception) file is closed – Darkgaze Jul 10 '18 at 12:30
  • @darkgaze `with open(...)` is definitely the best choice in modern Python. – mljrg Jul 10 '18 at 12:38
13

No need to close the file according to the docs if you use with:

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. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

user3765030
  • 353
  • 4
  • 7
-5

Here is example given which so how to use open and "python close

from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()

It's necessary to how many times you opened file have to close that times.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
Varun Chhangani
  • 1,116
  • 3
  • 13
  • 18
  • 1
    If an exception is raised after `open` but before `close`, the file won't be properly closed using this approach. Using `with` or `try`/`finally` closes the file properly even in the presence of exceptions. – Jon-Eric May 29 '14 at 15:54