【C#】【IO】【实例】接上一个统计的新功能

先用Python来创建多层级文件夹:

import os

root_path = r"C:\Users\Desktop\文案整理\Practice"

for item in range(1, 41):
    foldname = os.path.join(root_path, str(item))
    os.mkdir(foldname)

    foldname_son1 = os.path.join(foldname, str(item) + f'.{item}')
    os.mkdir(foldname_son1)

    for i_item in range(1, 501):
        foldname_son1_son = os.path.join(foldname_son1, str(i_item) + f'..{i_item}')
        os.mkdir(foldname_son1_son)

得到的树结构:

|-practice
|  |- 1
|  |  |- 1.1
|  |  |  |- 1..1
        ...
|  |  |  |- 500..500

读取遍历所有文件并将路径保存到文本中,然后再将指定图片保存到指定文件夹中:

 1 string fi = @"C:\Users\Desktop\文案整理\Practice"; // 整图文件夹
 2 string SN_txt = @"C:\Users\Desktop\文案整理\SN_NaemCollection.txt"; // 所有SN的路径记录
 3 string targefold = @"C:\Users\Desktop\文案整理\New"; // SN保存路径
 4 string SN = "302..302"; // SN编号
 5 Save_SNPath(fi, SN_txt);
 6 CopySN_Picture(FindSN_Picture(SN_txt, SN), targefold);
 7 
 8 void Save_SNPath(string fi, string SN_txt)
 9 {
10     // 清空文件内容
11     File.WriteAllText(SN_txt, String.Empty);
12     foreach (var item in Directory.GetDirectories(fi))
13         foreach (var i_item in Directory.GetDirectories(item))
14             foreach (var ii_item in Directory.GetDirectories(i_item))
15                 // 保存SN路径
16                 using (StreamWriter write = new StreamWriter(SN_txt, true))
17                     write.WriteLine(ii_item);
18 }
19 
20 string FindSN_Picture(string SN_txt, string SN)
21 {
22     // 查找SN_Picture
23     string [] f = File.ReadAllLines(SN_txt);
24     foreach (var item in f)
25         if (item.Contains(SN))
26         {
27             // 因 *..* 结构文件夹名会重复,所以需要再次遍历
28             string[] pic = Directory.GetFiles(item, "*.jpg");
29             if (pic.Length > 0)
30                 foreach(var i in pic)
31                     return i;
32         }
33     return "NULL";
34 }
35 
36 void CopySN_Picture(string soursefold, string targefold)
37 {
38     string ssfold = Path.Combine(targefold, DateTime.Now.ToString("d").Replace("/", "_") + "_SN");
39     // 创建当日SN文件夹
40     Directory.CreateDirectory(ssfold);
41 
42     // 复制SN中的图片至SN文件夹
43     File.Copy(soursefold, Path.Combine(ssfold, "2.jpg"));
44 }

后续将继续更新其他功能...

 

posted @ 2023-09-25 20:19  VanGoghpeng  阅读(32)  评论(0编辑  收藏  举报