I’m a python newbie (so far, I’m only proficient in bash scripting) and I’ve got a question on recursion and shutil.rmtree.
So, I have the following snippet…
keepthese = ('dir1', 'dir2', '.dotfile1', '.dotfile2', 'dir3', '.dotdir1')
dirpath = '/home/' + username + '/parentdir/'
killthese = [os.path.join('/home', username, '/parentdir', item) for item in os.listdir(dirpath) if item not in keepthese]
for x in killthese:
if os.path.isdir(x):
shutil.rmtree(x)
else:
os.remove(x)
(yes, I know it doesn’t seem very clean).
Essentially, I’ve got a set of filenames/directories. for this example, I’ll be using dir1.
Now, I have a directory layout that recurses in dir1, there will also be another directory named dir1, .dotdir, etc.
What I want to do is keep the first level of hierarchy (and obviously delete every file/directory in parentdir/ that does not match keepthese), but in every directory listed in keepthese, I want to remove everything (so I can’t do a recursion based on name only, or else I’ll delete the first level of keepthese iterates).
Does this make sense?
Assuming you want to:
Then something like this (untested!) script should work: