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