以前曾经问过这类问题,但我似乎无法通过我找到的帮助得到我想要的内容。
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 files!= 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
答案 0 :(得分:1)
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))
答案 1 :(得分:0)
我不会检查相等性,但是您的路径是否包含您要保留的文件夹。此示例改编自docs(稍微向上滚动以查看)
import os
# change this, obviously
root_dir = r'C:\Users\ben\Documents\Python Scripts\tmp'
keep = 'keep'
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):
print(os.path.join(root, name)) #change to os.remove once sure
for name in dirs:
if (keep not in root and keep not in name):
print(os.path.join(root, name)) # change to os.rmdir once sure
注意:根据keep
的详细程度,这可能无法删除您要删除的某些文件:即使rm_me\keep.txt
不在正确的目录中,也会保留r'C:\very_specific'
。详细的文件夹名称可以帮助解决这个问题:如果保持类似于Status
,则不会成为文件的名称,并且您将删除所需的所有内容。
答案 2 :(得分:0)
一种快速而肮脏的方法:
shutil.rmtree
销毁目录及其内容它可能会使用其他权限创建新的顶级目录,或者如果目录被写保护可能会失败,但在大多数情况下它会没事。
import shutil,os
root = r"C:\path\to\root"
shutil.rmtree(root)
os.mkdir(root)