【问题标题】:python os.remove can not access the filepython os.remove 无法访问该文件
【发布时间】:2016-01-03 21:40:26
【问题描述】:

我为什么会得到

Traceback(最近一次调用最后一次):文件“C:\temp\py\test.py”,第 8 行,在
os.remove( PATH ) PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:
'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 )

我错过了什么吗?

【问题讨论】:

  • f.close 应该是f.close()
  • 谢谢!!我想我在读一个变量..
  • 你是在引用方法而不是调用它

标签: python operating-system


【解决方案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)

【讨论】:

  • 或者哎呀,使用tempfile模块的TemporaryFileNamedTemporaryFile也为您完成删除。
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2013-05-11
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
相关资源
最近更新 更多