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

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


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”块中,因此它应该会自动关闭它。我究竟做错了什么?


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


ibeautiful
浏览 92回答 1
1回答

qq_遁去的一_1

此错误是由于您在此行再次打开文件并且从未关闭而引起的file = {'file': open(os.path.join(os.getcwd() , 'testfile.txt'), 'rb')}你也应该在这里使用with open
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python