我有這樣的代碼:我應該在移動它之前關閉文件嗎?
with open('foo.txt') as file:
...do something with file...
...move foo.txt to another place when it's still open...
有沒有與任何問題?
我有這樣的代碼:我應該在移動它之前關閉文件嗎?
with open('foo.txt') as file:
...do something with file...
...move foo.txt to another place when it's still open...
有沒有與任何問題?
這取決於操作系統。在基於Unix的系統中,這通常是安全的(您可以在打開文件的同時移動甚至刪除文件)。如果您嘗試移動/刪除打開的文件,Windows將產生Access Denied錯誤。
所以,最安全和便攜的方法是先關閉文件。請注意,with
子句會自動關閉文件,因此您只需執行以外的塊with
塊。
在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
不能移動的文件,因爲有人(你)已經持有它。您需要先關閉文件,然後才能移動它。
這也適用於Unix嗎? –
在Linux上正常工作。 – cdarke
最佳實踐與file
是close
和move
,因爲如果你不close
那麼它可能在某些操作系統創建的問題,像Windows
。
爲了讓您的代碼更加便攜,close
檔案在move
之前。
只是試試 – zhangxaochen
你只是在閱讀文件(代碼會提示是這種情況)?如果寫作你會有問題。根據操作系統的不同,您可能會得到不同的效果,以及您是否移動到不同的目錄或分區。請提供更多細節。 – cdarke
我只是在讀書。 –