如何在python 2.4中安全地打开/关闭文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3770348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to safely open/close files in python 2.4
提问by TM.
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.
我目前正在使用 Python 编写一个小脚本,以在我们的一台服务器上使用。服务器只安装了 Python 2.4.4。
I didn't start using Python until 2.5 was out, so I'm used to the form:
直到 2.5 出来我才开始使用 Python,所以我习惯了这样的形式:
with open('file.txt', 'r') as f:
# do stuff with f
However, there is no withstatement before 2.5, and I'm having trouble finding examples about the proper way to clean up a file object manually.
但是,with在 2.5 之前没有声明,而且我无法找到有关手动清理文件对象的正确方法的示例。
What's the best practice for disposing of file objects safely when using old versions of python?
使用旧版本的 python 时安全处理文件对象的最佳做法是什么?
采纳答案by Jon-Eric
See docs.python.org:
请参阅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.
完成文件后,调用 f.close() 关闭它并释放打开文件占用的所有系统资源。调用 f.close() 后,尝试使用文件对象将自动失败。
Hence use close()elegantly with try/finally:
因此close()优雅地使用try/finally:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
This ensures that even if # do stuff with fraises an exception, fwill still be closed properly.
这确保即使# do stuff with f引发异常,f仍会正确关闭。
Note that openshould appear outsideof the try. If openitself raises an exception, the file wasn't opened and does not need to be closed. Also, if openraises an exception its result is notassigned to fand it is an error to call f.close().
需要注意的是open应该出现之外的try。如果open本身引发异常,则文件未打开且不需要关闭。此外,如果open引发异常,则不f会将其结果分配给,调用f.close().
回答by Varun Chhangani
Here is example given which so how to use openand "python close
这是给出的示例,因此如何使用open和“pythonclose
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.
您打开文件的次数必须关闭该次。
回答by mljrg
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()
回答by user3765030
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 关键字是一种很好的做法。这样做的好处是文件在其套件完成后会被正确关闭,即使在途中引发异常也是如此。它也比编写等效的 try-finally 块要短得多:
>>> 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
更多信息:https: //docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

