【C#】【Python】【实例】统计多个文件夹下的图片

发布时间 2023-09-21 21:13:13作者: VanGoghpeng

因工作需要繁琐的进行同一目录多个文件夹下的图片统计,便使用代码来解决。

需求:统计的是多少个文件夹包含了图片,并非是统计有多少张图。

 

我们先用Python来创建一个现场环境(巩固巩固py知识):

 1 import os
 2 
 3 # 根目录
 4 root_path = r"C:\Users\Desktop\1111"
 5 
 6 for item in range(1, 20):
 7     # 在root_path下创建19个文件夹,名字是1-19
 8     foldname = os.path.join(root_path, str(item))
 9     os.mkdir(foldname)
10 
11     # 每个文件夹下创建一个jpg图片,并在1文件夹下多创建一张图
12     pic_name = os.path.join(foldname, str(item) + '.jpg')
13     if item == 1:
14         with open(pic_name[:-4] + '1.jpg', 'w'):
15             pass
16     with open(pic_name, 'w'):
17         pass
18 
19     # 每个文件下创建一个txt文本
20     txt_name = os.path.join(foldname, str(item) + '.txt')
21     with open(txt_name, 'w'):
22         pass

 

 

再使用C#(问就是工作环境只有这个)来遍历查找包含图片的文件夹个数:

 1 using System.IO;
 2 
 3 string root_fold = @"C:\Users\彭家屹\Desktop\文案整理\1111";
 4 int count = 0;
 5 
 6 // 遍历获取所有的文件夹
 7 foreach (var item in Directory.GetDirectories(root_fold))
 8 {
 9     // 获取当前文件夹下所有的的图片
10     string[] files = Directory.GetFiles(item, "*.jpg");
11     // 当长度为0时,说明没有图片,否则只执行一次+1操作
12     if (files.Length > 0)
13             count++;
14 }
15 Console.WriteLine(count);

 

至此就能到的所有包含图片的文件夹个数。