0

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)

glad_hd
  • 27
  • 3
  • Try adding time.sleep(5) before the last statement. – aedry Apr 21 '19 at 14:05
  • I think this is a duplicate of this [thread](https://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being#26741192). You might want to search up before posting. – Vasantha Ganesh Apr 21 '19 at 14:05

1 Answers1

1

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)
Mahmoud Elshahat
  • 1,873
  • 10
  • 24