这种类型的问题以前已经被问过了,但我似乎没有找到我想要的帮助。
这个问题有一个用户Iker的答案,其中用户提供的代码确实按照预期工作:它从文件夹中删除所有文件和目录,但不删除父文件夹本身。
我想进一步调整此代码,以便从父目录中删除所有文件,但不删除父目录,并且排除目录中的一个文件夹。
我正在使用的代码是:
我尝试在“for”语句后添加了一个“If”语句,基本上是这样说的:
如果文件不等于保留(keep) 并且我有一个变量“keep”指向父文件中名为“keep”的文件夹,以便此脚本将删除除父目录和父目录中名为“keep”的目录之外的所有内容。然而,在添加后,代码无法运行。
以下是我用的确切代码,其中包含打破代码的if语句:
这个问题有一个用户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”的文件夹,以便此脚本将删除除父目录和父目录中名为“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