'How to delete file after closing it in python?

What my code should do: It creates a temp image and opens it in Windows, after that, when user close that image, it should be deleted from the folder. How can i do that?

        if (selected_langs != ""):
            os.startfile('temp' + '.' +  format)
            os.remove('temp' + '.' +  format)

I thought that would work, but it says that "file was moved or deleted"



Solution 1:[1]

Check if file exists, then delete it:

import os

if os.path.exists("demofile.txt"):
    os.remove("demofile.txt")
else:
    print("The file does not exist") 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RiveN