gpt4 book ai didi

python - 读取后删除文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:56 24 4
gpt4 key购买 nike

在我的代码中,用户上传保存在服务器上的文件并使用服务器路径读取。阅读完文件后,我试图从该路径中删除该文件。但它给了我以下错误:

读取文件时出错。 [WinError 32] 进程无法访问该文件,因为它正被另一个进程使用

我正在使用 with 读取文件,我已经尝试了 f.close()f.closed 但它每次都出现同样的错误。

这是我的代码:

f = open(filePath)
with f:
line = f.readline().strip()
tempLst = line.split(fileSeparator)

if(len(lstHeader) != len(tempLst)):
headerErrorMsg = "invalid headers"
hjsonObj["Line No."] = 1
hjsonObj["Error Detail"] = headerErrorMsg
data['lstErrorData'].append(hjsonObj)
data["status"] = True

f.closed
return data

f.closed

在这段代码之后我调用了删除函数:

os.remove(filePath)

编辑: 使用 with open(filePath) as f: 然后尝试删除文件会出现同样的错误。

最佳答案

代替:

 f.closed

你需要说:

f.close()

closed 只是文件对象的 bool 属性,用于指示文件是否实际关闭。

close() 是实际关闭文件的文件对象上的方法。

旁注:在关闭文件句柄后尝试删除文件并非 100% 可靠。该文件可能仍在被病毒扫描程序或索引器扫描。或者其他一些系统 Hook 正在保留文件引用等...如果删除失败,请稍等一下,然后重试。

关于python - 读取后删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com