Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在多个文件夹中循环以清除每个文件夹中的图像_Python_Loops_Operating System - Fatal编程技术网

Python 在多个文件夹中循环以清除每个文件夹中的图像

Python 在多个文件夹中循环以清除每个文件夹中的图像,python,loops,operating-system,Python,Loops,Operating System,我有一个包含许多子文件夹的文件夹,每个文件夹中的图像都以png格式保存: 例如: emotion\angry emotion\disgusted emotion\fearful emotion\happy 我可以使用以下代码删除其中一个文件夹中的图像: folder_path = (r'C:\Users\emotion\angry') test = os.listdir(folder_path) for images in test: if images.endswith("

我有一个包含许多子文件夹的文件夹,每个文件夹中的图像都以png格式保存:

例如:

emotion\angry
emotion\disgusted
emotion\fearful
emotion\happy
我可以使用以下代码删除其中一个文件夹中的图像:

folder_path = (r'C:\Users\emotion\angry')
test = os.listdir(folder_path)
for images in test:
    if images.endswith(".png"):
        os.remove(os.path.join(folder_path, images))

我如何创建一个循环来循环emotion/中的每个子文件夹?
由于我不想手动写出所有代码来清除所有文件夹…

您可以使用
glob
模式列出文件,并使用正常的
操作系统删除它们。删除

import os
import glob

fileList = glob.glob('C:\Users\emotion\*\*.png')

for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)