在我的项目中,我必须将一些文本作为文件上传到烧瓶服务器。我尝试了以下方法,但遇到了一些问题:
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”块中,因此它应该会自动关闭它。我究竟做错了什么?
任何帮助和建议将不胜感激。
qq_遁去的一_1
相关分类