我在使用 Python 脚本查找和删除空文件夹时遇到问题。 我有一些目录或多或少是这样的文件:
A/
--B/
----a.txt
----b.pdf
--C/
----d.pdf
我正在尝试删除所有非 PDF 文件,然后删除所有空文件夹。我可以删除我想要的文件,但我无法获得空目录。我做错了什么?
os.chdir(path+"/"+name+"/Test Data/Checklists")
pprint("Current path: "+ os.getcwd())
for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists"):
for name in files:
if not(name.endswith(".pdf")):
os.remove(os.path.join(root, name))
pprint("Deletting empty folders..")
pprint("Current path: "+ os.getcwd())
for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists", topdown=False):
if not dirs and not files:
os.rmdir(root)
最佳答案
使用安装函数
os.removedirs(path)
这将删除目录,直到父目录不为空。
关于Python:递归删除空文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34900289/