Search code examples
pythonfilepython-requestspermission-denied

close a file sent to url using Requests - Python


In my project i have to upload some text as a file to a flask server. i have tried the following approach but am facing some issues:

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'))

As i have to upload only text as a file so i have created a temporary file, wrote the contents, and deleted it, but this code gives me the following error

Traceback (most recent call last):
File "D:\PythonTest\test.py", line 121, in upload
os.remove(os.path.join(os.getcwd(), 'testfile.txt'))
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:\PythonTest\testfile.txt'

As much as i can understand from the 'error report', it is caused because the file is open in the post request i had made. But i have enclosed the post request in the 'with' block so it should close it automatically. What am i doing wrong?

Any help and suggesstions would be appreciated.


Solution

  • This error is caused due to you open file again in this line and never close

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

    You should use with open here too