我有一个包含很多子文件夹的文件夹,每个文件夹中的图片都保存为 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
模式列出文件并使用普通的 os.remove
删除它们。
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)
关于python - 循环遍历多个文件夹以清除每个文件夹中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67251715/