How to safely open/close files in python 2.4
我目前正在编写一个小脚本,在我们的一个使用python的服务器上使用。服务器只安装了python 2.4.4。
直到2.5版问世,我才开始使用python,所以我习惯了这种形式:
1 2 | with open('file.txt', 'r') as f: # do stuff with f |
但是,在2.5之前没有
在使用旧版本的python时,安全地处理文件对象的最佳实践是什么?
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.
四个
1 2 3 4 5 6 | f = open('file.txt', 'r') try: # do stuff with f finally: f.close() |
本ensures,即使在异常
注意
在上面的解决方案,可在这里:
1 2 3 4 5 6 | f = open('file.txt', 'r') try: # do stuff with f finally: f.close() |
如果(你永远不会知道发生什么坏……)开通后的成功尝试和文件之前,文件将不闭合,从而更安全的解决方案是:A
1 2 3 4 5 6 7 8 9 | f = None try: f = open('file.txt', 'r') # do stuff with f finally: if f is not None: f.close() |
不需要关闭文件按《文件如果你使用的是:
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:
1 2 3 4 | >>> with open('workfile', 'r') as f: ... read_data = f.read() >>> f.closed True |
更多在这里:http://docs.python.org教程/ / 2 / inputoutput.html #学院的文件对象的方法
这里是没有这样的例子,如何使用Python和
1 2 3 4 5 6 7 8 9 10 11 12 | 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() |
它必要你有多少次打开文件关闭那个时代。