使用 Python 3.0 截取后无法删除屏幕截图(该进程无法访问该文件,因为它正被另一个进程使用)

Can't delete screenshot after I just took it using Python 3.0 (The process cannot access the file because it is being used by another process)

我正在尝试制作一个 python 3 脚本,用于截取屏幕截图,将其上传到网站,然后从计算机中删除屏幕截图。当我尝试使用 os.remove() 删除文件时出现问题。我收到以下错误:"The process cannot access the file because it is being used by another process" 关于如何解决此问题的任何想法?


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)

你在open(file_name, 'rb')中打开文件并且在remove()之前没有关闭它的问题

试试这个:

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)