[python] How to safely open/close files in python 2.4

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?

This question is related to python file-io python-2.4

The answer is


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.


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


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()