Python递归删除目录中的文件/文件夹,但不删除父目录或特定文件夹

标签 python windows

这种类型的问题以前有人问过,但我似乎无法通过我找到的帮助得到我想要的东西。

This question有一个 answer by user Iker ,其中用户提供的代码确实完全按预期工作:它从文件夹中删除所有文件和目录,但不删除父文件夹本身。

我想通过删除父目录中的所有文件来进一步调整这一点,但不删除父目录,并且我想排除目录中的文件夹。

我使用的代码是:

import os
import shutil

files = '[the path to my folder]'

for root, dirs, files in os.walk(files):
    for f in files:
        os.unlink(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

我试过在“for”语句之后添加一个“If”语句,基本上说:

如果文件 != 保留

我有一个变量“keep”指向父文件中名为“keep”的文件夹,因此该脚本将删除除父目录和父目录中名为“keep”的目录之外的所有内容。但是,添加之后,代码不起作用。

这是我的确切代码,带有中断代码的 if 语句:

import os
import shutil

files = '[the path to the parent folder'
keep = '[the path to the "keep" folder]'

for root, dirs, files in os.walk(files):
    for f in files:
        if files != keep:
            os.unlink(os.path.join(root, f))
    for d in dirs:
        if files != keep:
            shutil.rmtree(os.path.join(root, d))

我确定我正在做的事情非常明显,但对我来说并不明显,因此我们将不胜感激。

谢谢!

编辑:根据下面 Ben 的回答,这是对我有用的代码:

import os
import shutil

root_dir = r'[path to directory]' # Directory to scan/delete

keep = 'keep' # name of file in directory to not be deleted

for root, dirs, files in os.walk(root_dir):
    for name in files:
        # make sure what you want to keep isn't in the full filename
        if (keep not in root and keep not in name):
            os.unlink(os.path.join(root, name)) # Deletes files not in 'keep' folder
    for name in dirs:
        if (keep not in root and keep not in name):
            shutil.rmtree(os.path.join(root, name)) # Deletes directories not in 'keep' folder

最佳答案

修改版本:如果您使用的是 Windows 操作系统,它可能会有所帮助

import os
import shutil

root_dir = r'C:\Users\Venus\scarap'

for root, dirs, files in os.walk(root_dir):

    for name in files:
            print(os.path.join(root, name)) 
            os.remove(os.path.join(root, name))
    for name in dirs:
            print(os.path.join(root, name))
            shutil.rmtree(os.path.join(root, name))

关于Python递归删除目录中的文件/文件夹,但不删除父目录或特定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267807/

相关文章:

windows - 为什么 windows shell 的 for 命令会替换分号?

windows - Windows 文件名中的分号?

windows - Jenkins 如何使用 Windows 批处理命令使用环境变量?

python - 使用python绘制相关矩阵

python - 使用 Pandas 将同一类的两行合并

python - @ 运算符与 ndarray 或矩阵操作数出现新的意外操作数错误

python - 如何通过python计算属于字符串列表的每个字符串长度?

python - Kivy的几个属性的继承

c - LoadLibrary 不重用已加载的库

windows - 为什么 Windows 8 在登录 MS 帐户后发送不同的授权 header