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