3 回答

TA贡献1811条经验 获得超6个赞
我喜欢Daniel的回答,但我意识到将文件重命名为它已经拥有的名称更安全,更简单。这解决了他回答中提到的问题。我只是在评论中说过这一点,但我没有要点。这是代码:
import os
f = 'C:/test.xlsx'
if os.path.exists(f):
try:
os.rename(f, f)
print 'Access on file "' + f +'" is available!'
except OSError as e:
print 'Access-error on file "' + f + '"! \n' + str(e)

TA贡献1777条经验 获得超10个赞
您可以使用下一个函数检查文件上是否有句柄(请记住将完整路径传递给该文件):
import psutil
def has_handle(fpath):
for proc in psutil.process_iter():
try:
for item in proc.open_files():
if fpath == item.path:
return True
except Exception:
pass
return False
添加回答
举报