python - 循环遍历多个文件夹以清除每个文件夹中的项目

标签 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"):
        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/

相关文章:

java - 如何在递增另一个变量时递增一个变量?

c - 如何使用 read 系统调用读取数据输入

variables - METAPOST:在标签中使用循环变量

java - 当顾客在昏昏欲睡的理发师问题中等待理发时信号量值?

linux - 递增时钟

python - 如何在 python 中定义/格式化日期和时间

python - 从 OLS 回归结果中读取 coef 值

python - get_includes 找不到标准库头文件

python - 我无法修复此代码中的错误。解释器说, "TypeError: unsupported operand type(s) for -: ' str' 和 'int' "

java - 使 Java 程序循环直到输入 x?