2013-05-12 48 views
1

有時,當我打開一個文件進行讀取或寫入在PythonPython的讀/寫文件,但不關閉

f = open('workfile', 'r') 

f = open('workfile', 'w') 

我讀/寫文件,然後在最後我忘記做f.close()。在完成所有讀/寫操作後,或在代碼完成處理後,是否有辦法自動關閉?

+0

您有什麼版本的Python?你可能想用'with ... as'語法。 – squiguy 2013-05-12 01:41:42

+0

我正在使用Python 2.6.5。它是否與該語法兼容? – 2013-05-12 01:44:44

+0

是的,請參閱[this](http://stackoverflow.com/questions/14776853/python-with-as)回答。 – squiguy 2013-05-12 01:45:52

回答

4
with open('file.txt','r') as f: 
    #file is opened and accessible via f 
    pass 
#file will be closed before here 
1

你總是可以使用以...爲聲明

with open('workfile') as f: 
    """Do something with file""" 

,或者你也可以使用一個嘗試... finally塊

f = open('workfile', 'r') 
try: 
    """Do something with file""" 
finally: 
    f.close() 

雖然自你說你忘了添加f.close(),我猜... with ... as語句對你來說是最好的,因爲它簡單,它是h以查看不使用它的原因!

0

無論你做你的文件,你讀它在後,這是你應該如何閱讀和寫回:

$蟒蛇myscript.py sample.txt的sample1.txt

然後第一參數(sample.txt)是我們的「oldfile」,第二個參數(sample1.txt)是我們的「newfile」。然後,您可以將以下代碼寫入名爲「myscript.py」的文件中

from sys import argv 
    script_name,oldfile,newfile = argv 
    content = open(oldfile,"r").read() 
    # now, you can rearrange your content here 
    t = open(newfile,"w") 
    t.write(content) 
    t.close() 
+0

不使用上下文管理(或try/finally)構造來確保資源始終關閉是一個壞習慣。如果這段代碼被轉換成函數,它會在任何錯誤時泄漏文件描述符。 – ankostis 2015-02-17 00:49:53