当前位置:网站首页>将同一文件夹下的大量文件根据设定分至多组

将同一文件夹下的大量文件根据设定分至多组

2022-06-10 17:37:00 _囧囧_

将同一文件夹下的大量文件根据设定分至多组

  1. 需求分析
    recon文件夹下存在大量文件,观察文件名,我们设计将文件按照recon_后的第一个数字进行分组,那么最终产生的文件夹应为0,1,…,11
    在这里插入图片描述
  2. 编写程序
    基于上述假象,我们编写了如下程序,将其复制在recon文件夹下运行即可。
    #!/usr/bin/env python
    import subprocess, threading, time, shutil, os, sys
    import re
    
    
    file_list = os.listdir()
    
    file_set = {
          }
    pattern = 'recon_(\d*)_'
    
    for file in file_list:
        result = re.match(pattern, file)
        if result == None:
            continue
    
        if result.group(1) not in file_set.keys():
            file_set[result.group(1)] = []
    
        file_set[result.group(1)].append(file)
    
    for key in file_set.keys():
        os.path.exists(key) or os.mkdir(key)
    
        for item in file_set[key]:
            mv_cmd = ['mv', item, key]
            subprocess.call(mv_cmd)
    
    print(file_set.keys())
    
    实验结果如下所示:
    在这里插入图片描述
  3. 扩展
    如果根据数量进行划分,例如每个文件夹固定数量的文件,我想也是同样的逻辑,首先获取全部文件名,剔除split.py,创建新文件夹,划分文件。
原网站

版权声明
本文为[_囧囧_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_40502018/article/details/125009806