舒蒂尔.rmtree在python中的混合层次结构级别中

2024-06-16 11:58:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个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迭代的第一级)。在

这有道理吗?在


Tags: pathin目录homeforosusernameitem
2条回答

我试着用手术室步行像是。。。在

for root, dirs, files in os.walk(dirpath, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        if name not in keepthese:
            os.rmdir(os.path.join(root, name))

假设您想:

  • 删除给定根目录中的所有内容,禁止列出例外目录
  • 删除每个例外目录中的所有内容

然后像这样(未经测试!)脚本应该起作用:

import sys, os, shutil

def prune(dirpath, exceptions=()):
    for name in os.listdir(dirpath):
        path = os.path.join(dirpath, name)
        if name in exceptions:
            prune(path)
        else:
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)

exceptions = ('dir1', 'dir2', '.dotfile1', '.dotfile2', 'dir3', '.dotdir1')

if __name__ == '__main__':

    root = os.path.join('/home', sys.argv[1], 'parentdir')

    prune(root, exceptions)

相关问题 更多 >