在我的項目中,我必須將一些文本作為文件上傳到燒瓶服務器。我嘗試了以下方法,但遇到了一些問題: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”塊中,因此它應該會自動關閉它。我究竟做錯了什么?任何幫助和建議將不勝感激。
關閉使用請求發送到 url 的文件 - Python
ibeautiful
2023-05-16 16:46:15