gmolau
gmolau

Reputation: 3005

Python: How to ensure that a file gets deleted when the program finishes?

I have several files that absolutely have to be deleted when the program finishes. I don't really want to use tempfile.TemporaryFile because the files have to be passed around quite a bit, and be used for command output redirection in os.system() calls. So I would use tempfile.mkstemp, but these don't get deleted automatically. I thought about wrapping my main method in a try-finally like this:

if __name__ == "__main__":
    try:
        main()
    finally:
        os.remove(tempfile)

but that looks rather questionable. Is there a better way?

Upvotes: 3

Views: 2630

Answers (1)

gmolau
gmolau

Reputation: 3005

My question has been answered by the comments above, but I've found another neat solution that I'll just leave here for future reference: atexit

Upvotes: 1

Related Questions