import os def del_none_folder(path): max_len = len(path.split('\')) for folder,subfolder,file in os.walk(path): # 获取最大路径长度 if len(folder.split('\')) > max_len: max_len = len(folder.split('\')) # 获取相对路径的长度 max_len = max_len - len(path.split('\')) # 对长度进行遍历删除 for i in range(max_len): for fo,sf,f in os.walk(path): # 如果目录下没有文件夹和文件,说明此路径是空的,就删掉 if not sf and not f: os.rmdir(fo) print('Deleted: {}'.format(fo)) print('Done.') del_none_folder(r'C:UserszhongDesktopa')