Serban Razvan Serban Razvan - 1 month ago 6x
Python Question

How to make scripts auto-delete at the end of execution?

Is it possible to make a python script that will delete the .py file at the end of its execution (self-delete) in windows?


I'm not sure deleting a file while it's in memory would be a good idea. Try running a batch file from the script which closes the script process, then deletes the script file.

There may be a native method to self destruct a script, but I am not aware of it.

EDIT: Here is a simple example of how you could accomplish this using the method I described:

In the script

# C:\
import os

In the batch

# C:\sampleBatch.bat
TASKKILL /IM "process name" #For me, this was "ipy64.exe" because I use IronPython.
DEL "C:\"

You may not even need to kill the process to delete the file, but it is safer to do so. Hope this helps.