- VC Healy
- Nov 1, 2020
- 2 min read
After writing a script to create folders in Python I wanted to write something that would delete the same files.
Delete a single file was simple, drop the script into the appropriate folder and run, I had a similar situation with an empty folder. Then there was code to delete a folder with content without concern for the file and folder content of that folder.
The introduction of a check for file content within a folder prior to the deletion of the folder was next on my list and this worked with one exception. If the folder containing an empty folder an error would be given in trying to delete the folder with such content. As the empty folder was not seen as content within a folder.
I found a way to delete subfolders unfortunately the order of deletion was from top-down,
As the folders were generated by os.walk, this meant that the top-level folder was deleted first but then the code would try to delete the next level down of folders but would fail.
My solution for this was to convert the dirs information extracted by os.walk into a list. With the list built, pop an item from the list. This item would be the lowest level of the subfolder in the folder tree and thus could be deleted without error. The pop would continue up the tree until the root level and would stop.
Overall, the code would delete the files from the top-level to the lowest level in the folder tree. Then the code deletes the folders from the lowest on the folder tree. Preventing any error.
Asking the user to delete a file or folder gave full control of the deletion process if they wanted it.
In each case above if a file or folder did not exist the code would return an appropriate message rather than give an error.
Giving an Argument
The code was designed to accept an argument. This allowed control of the file or folder to be deleted in relation to the location of the code. Rather than this being hardcoded.
One downside to this was that the argument was a string and not a raw string, that was required to join to the root path of the script if required.
My solution to this was to run the argument through a conversion method first, rather than put the conversion method in each script.
Raw Method

The Other Scripts

The Main Script
