循环遍历多个文件夹以清除每个文件夹中的项目
我有一个文件夹,其中包含很多子文件夹,每个文件夹中的图像都保存为 png:
例如 :
emotionangry
emotiondisgusted
emotionfearful
emotionhappy
我可以使用以下代码删除其中一个文件夹中的图像:
folder_path = (r'C:Usersemotionangry')
test = os.listdir(folder_path)
for images in test:
if images.endswith(".png"):
os.remove(os.path.join(folder_path, images))
如何创建一个循环来遍历每个情绪/子文件夹?因为我不想手动写出所有代码来清除所有文件夹......
回答
您可以使用glob模式列出文件并使用普通的os.remove.
import os
import glob
fileList = glob.glob('C:Usersemotion**.png')
for filePath in fileList:
try:
os.remove(filePath)
except:
print("Error while deleting file : ", filePath)