我是python和尝试的新手。是否有可能走一棵树搜索特定的文件名,找到文件后删除整个文件夹是否找到该文件?
以下有效,但只删除文件,我想在找到addon.sxm时删除整个文件夹
if os.path.exists(Addons):
for root, dirs, files in os.walk(Addons):
package_count = 0
package_count += len(files)
if package_count > 0:
for f in files:
if fnmatch.fnmatch(f, 'addon.sxm'):
try:
os.remove(os.path.join(root, f))
except:
pass
else:
pass
答案 0 :(得分:1)
而不是 os.remove(os.path.join(root,f))使用 shutil.rmtree(root); 它将删除文件所在的目录
import os
import fnmatch
import shutil
Addons="/path/to/my/folder/"
if os.path.exists(Addons):
for root, dirs, files in os.walk(Addons):
package_count = 0
package_count += len(files)
if package_count > 0:
for f in files:
print(f)
if fnmatch.fnmatch(f, 'addon.sxm'):
try:
shutil.rmtree(root);
except:
pass
else:
pass