2014-02-27 41 views
2

我有這樣的代碼:我應該在移動它之前關閉文件嗎?

with open('foo.txt') as file: 
    ...do something with file... 
    ...move foo.txt to another place when it's still open... 

有沒有與任何問題?

+0

只是試試 – zhangxaochen

+0

你只是在閱讀文件(代碼會提示是這種情況)?如果寫作你會有問題。根據操作系統的不同,您可能會得到不同的效果,以及您是否移動到不同的目錄或分區。請提供更多細節。 – cdarke

+0

我只是在讀書。 –

回答

5

這取決於操作系統。在基於Unix的系統中,這通常是安全的(您可以在打開文件的同時移動甚至刪除文件)。如果您嘗試移動/刪除打開的文件,Windows將產生Access Denied錯誤。

所以,最安全和便攜的方法是先關閉文件。請注意,with子句會自動關閉文件,因此您只需執行以外的with塊。

3

在Windows上:

>>> import os 
>>> with open('old.txt') as file: 
     os.rename('old.txt', 'new.txt') 

Traceback (most recent call last): 
    File "<pyshell#4>", line 2, in <module> 
    os.rename('test.txt', 'newtest.txt') 
WindowsError: [Error 32] The process cannot access the file because it is being used by another process 

不能移動的文件,因爲有人(你)已經持有它。您需要先關閉文件,然後才能移動它。

+0

這也適用於Unix嗎? –

+1

在Linux上正常工作。 – cdarke

0

最佳實踐與fileclosemove,因爲如果你不close那麼它可能在某些操作系統創建的問題,像Windows

爲了讓您的代碼更加便攜,close檔案在move之前。

相關問題