Python Requests POST / Upload Image File

Question:

How can I os.remove() this image after it has been uploaded? I believe that I need to close it somehow.

import requests, os

imageFile = "test.jpg"

myobj = {'key': 'key', 'submit':'yes'}
up = {'fileToUpload':(imageFile, open(imageFile, 'rb'), 'multipart/form-data')}
r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
sendTo = r.text
os.remove(imageFile)

The above generates:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
Asked By: Ned Hulton

||

Answers:

You never closed the file after opening.

Try:

import requests, os

imageFile = "test.jpg"

with open(imageFile, 'rb') as f:
    myobj = {'key': 'key', 'submit':'yes'}
    up = {'fileToUpload':(imageFile, f, 'multipart/form-data')}
    r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
    sendTo = r.text

os.remove(imageFile)
Answered By: jeandemeusy

You need to restructure your code so that you are using a context manager:

import requests, os

imageFile = "test.jpg"

myobj = {'key': 'key', 'submit':'yes'}
with open(imageFile, "rb") as im:
    up = {'fileToUpload':(imageFile, im, 'multipart/form-data')}
    r = requests.post('https://website/uploadfile.php', files=up, data = myobj)
    sendTo = r.text
os.remove(imageFile)

When you exit the with block, the file will automatically be closed, the lock will be released, and you can then delete it.

Answered By: MattDMo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.