如何在 python 2.4中安全地打开/关闭文件

我目前正在编写一个小脚本,以便在我们的一台服务器上使用 Python。服务器只安装了 Python 2.4.4。

直到2.5版本发布之后,我才开始使用 Python,所以我已经习惯了这种形式:

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

但是,在2.5之前没有 with语句,我很难找到有关手动清理文件对象的正确方法的示例。

当使用旧版本的 python 时,安全处理文件对象的最佳实践是什么?

148286 次浏览

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

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.

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

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