Search code examples
pythondelete-filetermination

Trigger code on program termination


My script creates files to store data for the duration of its run time, I would like to delete these files on termination of my program. Is this possible?

I DO NOT want suggestions for a work around ... like 'don't create files'.

Much appreciated!


Solution

  • What about the os module of Python ? There is a "remove()" method to do what you want.

    See the documentation

    To handle the exit of your program, you can use atexit module.

    Example:

    import os
    
    def delete_file(name):
        os.remove(name)
    
    import atexit
    atexit.register(delete_file, file_path)
    

    file_path is the file to delete.