Python 在多个文件夹中循环以清除每个文件夹中的图像
我有一个包含许多子文件夹的文件夹,每个文件夹中的图像都以png格式保存: 例如: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("
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)