【问题标题】:looping through multiple folders to clear items in each folder循环遍历多个文件夹以清除每个文件夹中的项目
【发布时间】:2021-07-18 22:42:34
【问题描述】:

我有一个包含很多子文件夹的文件夹,每个文件夹中都保存为 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/中的每个子文件夹? 因为我不想手动写出所有代码来清除所有文件夹...

【问题讨论】:

    标签: python loops operating-system


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 2018-08-14
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多