python 递归删除目录和文件_Python递归地删除目录中的文件/文件夹,但不删除父目录或特定的文件夹...

这类问题以前也有人问过,但从我找到的帮助来看,我似乎不能确切地得到我想要的东西。在

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”语句,它基本上是这样说的:

如果文件!=保持

在父目录中保留一个名为“删除父目录”的所有内容,并将其保存在一个名为“父”的目录中,而“父级”脚本除外。但是,在添加了这些之后,代码就不起作用了。在

下面是我的确切代码,其中if语句破坏了代码:

^{pr2}$

我确信我所做的是显而易见的,但对我来说并不明显,所以任何帮助都将不胜感激。在

谢谢!在

编辑:根据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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值