2015-10-06 102 views
0

爲什麼我收到蟒蛇os.remove不能訪問該文件

Traceback (most recent call last): File "C:\temp\py\tesst.py", line 8, in <module>
os.remove(PATH) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
'C:\temp\py\test.txt'

import os 
PATH = r'C:\temp\py\test.txt' 

f = open ( PATH,'w') 
f.write('test\n') 
f.close; 

os.remove(PATH) 

我缺少的東西?

+1

'f.close'應該是'f.close()' –

+0

謝謝!我想我正在讀一個變量.. – user929542

+0

你引用的方法,而不是調用它 –

回答

1

您正在致電f.close而不是f.close()。上下文打開文件會更好,所以它會自動關閉。

import os 
PATH = r'C:\temp\py\test.txt' 

with open(PATH, 'wb') as f: 
    f.write('test\n') 

os.remove(PATH) 
+0

或者,你也可以使用'tempfile'模塊的'TemporaryFile'或'NamedTemporaryFile'來完成刪除操作。 – ShadowRanger