Search code examples
pythonpathdirectorydelete-directory

Making a Script that deletes its own folder when it finishes


Is it possible to make a script delete its own folder? clearly there are some issues here but I feel like it might be possible.

Essentially what i'm trying to create is a script that once it's finished doing it's thing that will delete it's own folder and a few other files. But I'm mainly having an issue with trying to tell it to delete itself as a method of closing itself.

As a final action or in a sense telling the pc to do one more action after its closed itself

Any help would be greatly appreciated :)

Tltr;can an application can tell windows to do a command after it close's it self


Solution

  • Yes, you can do this. The script will be loaded into memory when it runs, so it can delete its parent directory (and therefore itself) directly from the script without any issues. Just use shutil.rmtree rather than os.rmdir, because os.rmdir can't remove a directory that isn't empty.

    Here's a one-liner that will do it (be careful running this in a directory with stuff you don't want deleted!) shutil.rmtree(os.path.dirname(os.path.realpath(__file__)))