我是一个python新手(到目前为止,我只精通bash脚本),我有一个关于递归和shutil.rmtree
的问题。在
所以,我有以下片段。。。在
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)
(是的,我知道它看起来不太干净)。在
基本上,我有一组文件名/目录。对于本例,我将使用dir1
。在
现在,我有一个在dir1
中递归的目录布局,还有另一个名为dir1
,.dotdir
等的目录
我想做的是保留层次结构的第一级(显然删除parentdir/中与keepthese不匹配的每个文件/目录),但是在keepthese中列出的每个目录中,我想删除所有的东西(因此我不能只基于名称进行递归,否则我将删除keepthese
迭代的第一级)。在
这有道理吗?在
我试着用手术室步行像是。。。在
假设您想:
然后像这样(未经测试!)脚本应该起作用:
相关问题 更多 >
编程相关推荐