I’m trying to remove a directory using python but I do not want to recursively remove the whole directory path in the process: i.e
/home/dir/dir/dirtoberemoved
So I don’t want to remove anything at a higher level just the one directory and all its contents. I’ve been looking on stackoverflow to research this question and most answers have included using the shutil module which I am unfamiliar with, looking at the python documentation for the module it says ‘Delete an entire directory tree’
If I do something like this:
if os.path.exists("/home/dir/dir/dirtoberemoved");
shutil.rmtree("/home/dir/dir/dirtoberemoved");
or
shutil.rmtree("/dirtoberemoved");
Will the entire path be removed? If so is there any good way just to delete one non-empty directory in python without deleting higher level directories?
You need to specify the whole path to the directory to be removed. Only the last part of the path will be deleted, the
/home/dir/dir/part will be untouched.The deletion refers to any sub-directories contained within the named path, so if there is a
/home/dir/dir/dirtoberemoved/foosub-directory it’ll be removed together with it’s parent.