【问题标题】:Delete a current directory based on If condition根据If条件删除当前目录
【发布时间】:2017-12-22 12:49:14
【问题描述】:

以下代码计算每个子目录中的图像数量。如果子目录中的图像超过 2 个,如何删除子目录。
n13 是主目录=> 有 300 个子目录(1...300)=> 每个子目录都有图片

输出:
图片:2,目录:1
图片:3,目录:2
图片:4,目录:3

import os
path='C:/n13/'
def count_em(path):
    x = 0
    for root, dirs, files in os.walk(path):
       files_count = (len(files))
       x = x + 1
       print("Images:",files_count,"Directory:",x)
    return files_count

【问题讨论】:

  • 如果 files_count >2 : shutil.rmtree(os.walk(path))
  • error "lstat: 路径应该是字符串、字节或 os.PathLike,而不是生成器"
  • os.walk(path) 在这个地方给出子目录路径

标签: python python-3.x count subdirectory shutil


【解决方案1】:

您可以使用shutil.rmtree() 删除文件夹及其子目录和文件。

import os
import shutil

path='C:/n13/'

def count_em(path):
    x = 0
    files_count = 0
    for root, dirs, files in os.walk(path):
        files_count = (len(files))
        if files_count >= 2:
            shutil.rmtree(root)
        x = x + 1
        print("Images:", files_count, "Directory:", x)
    return files_count


count_em(path)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2010-10-07
  • 1970-01-01
  • 2022-06-28
相关资源
最近更新 更多