I am trying to make a python 3 script that takes a screenshot, uploads it to a website and then deletes the screenshot from the computer. The problem occurs when I try to delete the file using os.remove() . I get the following error: "The process cannot access the file because it is being used by another process" Any ideas on how to fix this?
pic = pyautogui.screenshot()
file_name = 'ss-' + nume + "-" + str(random.randint(0, 1000)) + '.png'
pic.save(file_name)
form_data = {
'image': (file_name, open(file_name, 'rb')),
'nume': ('', str(nume)),
}
response = requests.post('https://website.com', files=form_data)
print(response)
k = 1
os.remove(file_name)
The problem you opened the file in open(file_name, 'rb')
and didn't close it before remove()
try this:
pic = pyautogui.screenshot()
file_name = 'ss-' + nume + "-" + str(random.randint(0, 1000)) + '.png'
pic.save(file_name)
f = open(file_name, 'rb') # open the file
form_data = {
'image': (file_name, f),
'nume': ('', str(nume)),
}
response = requests.post('https://website.com', files=form_data)
print(response)
k = 1
f.close() # close file before remove
os.remove(file_name)