读取后删除文件

Tah*_*bal 5 python file

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

An error occurred while reading file. [WinError 32] The process cannot access the file because it is being used by another process

我正在使用 读取文件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
Run Code Online (Sandbox Code Playgroud)

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

os.remove(filePath)
Run Code Online (Sandbox Code Playgroud)

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

sel*_*bie 3

代替:

 f.closed
Run Code Online (Sandbox Code Playgroud)

你需要说:

f.close()
Run Code Online (Sandbox Code Playgroud)

closed只是文件对象上的一个布尔属性,用于指示文件是否实际上已关闭。

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

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