Skip to main content
 首页 » 编程设计

python之python 中混合层次结构级别的 shutil.rmtree

2025年05月04日12bonelee

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

这有意义吗?

请您参考如下方法:

假设你想:

  • 删除给定根目录中的所有内容,排除异常(exception)目录列表
  • 删除每个异常(exception)目录中的所有内容

然后像这样(未经测试!)的脚本应该可以工作:

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)