使用请求关闭发送到url的文件-Python

问题描述

在我的项目中,我必须将一些文本作为文件上传到Flask服务器。 我尝试了以下方法,但遇到了一些问题:

with open(os.path.join(os.getcwd(),"testfile.txt"),'w+') as myFile:
    myFile.write(content)
    myFile.close()

file = {'file': open(os.path.join(os.getcwd(),'testfile.txt'),'rb')}
data = {'data': somedata}
headers = {'Accept-Encoding': 'identity'}

with requests.post(upload_url,files=file,data=data,headers=headers) as resp:
    html = resp.content  

os.remove(os.path.join(os.getcwd(),'testfile.txt'))

由于我只需要上传文本作为文件,所以我创建了一个临时文件,写入了内容,然后将其删除,但是此代码给了我以下错误

回溯(最近通话最近):
上传中的文件“ D:\ PythonTest \ test.py”,第121行,
os.remove(os.path.join(os.getcwd(),'testfile.txt'))
PermissionError:[WinError 32]该进程无法访问文件,因为该文件正在被另一个进程使用:'D:\ PythonTest \ testfile.txt'

据我从“错误报告”中了解到的,这是由于文件在我发出的发帖请求中打开而引起的。但是我已经将发布请求封装在“ with”块中,因此它应该自动关闭它。我在做什么错了?

任何帮助和建议,我们将不胜感激。

解决方法

此错误是由于您在此行中再次打开文件而永不关闭

引起的

file = {'file': open(os.path.join(os.getcwd(),'testfile.txt'),'rb')}

您也应该在此处使用 打开