递归删除空件夹
递归删除空文件夹
Python中的os.walk提供了一种从内到外的遍历目录树的方法(设置topdown=False),这样由内到外判断当前目录树下是否有文件和文件夹,如果都没有则意味着当前目录树为空文件夹,os.rmdir删除即可。
import os for root, dirs, files in os.walk(path, topdown=False): if not files and not dirs: os.rmdir(root)
如果在遍历文件夹同时,先做一些操作(比如删除文件os.remove),然后再判断此时文件夹是否为空,为空则删除,需要用os.listdir判断当前文件夹是否为空。
import os
for root, dirs, files in os.walk(path, topdown=False):
for file in files:
if file.endwith('.jpg'):
file = os.path.join(root, file)
os.remove(file)
if not os.listdir(root):
os.rmdir(root)参考:https://www.cnblogs.com/michaelcjl/p/12509546.html
本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work
尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。
GitHub登录