Easy way to delete a shelve .dat file left behind by my Python program?
Question
So I have a python program that ends up leaving a .dat file from the shelve
function behind after execution. I would like my program to delete or clear that file once it is done. My textbook only mentions how to create a .dat file but not how to clear it. Any good commands out there to take care of this? I don't need the .dat file again after my program runs to completion.
Solution
This is easy:
import sys, os
sys.atexit.register( os.remove, path_to_file )
runs os.remove( path_to_file )
when the Python interpreter exists in a normal (not killed/crashed) way. But you need to make sure the file is closed by then.
OTHER TIPS
Register an atexit
handler to do the cleanup for you (as described in the documentation here).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow