将同一文件夹下的大量文件根据设定分至多组
- 需求分析
在recon文件夹下存在大量文件,观察文件名,我们设计将文件按照recon_后的第一个数字进行分组,那么最终产生的文件夹应为0,1,…,11。

- 编写程序
基于上述假象,我们编写了如下程序,将其复制在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())

- 扩展
如果根据数量进行划分,例如每个文件夹固定数量的文件,我想也是同样的逻辑,首先获取全部文件名,剔除split.py,创建新文件夹,划分文件。
本文介绍了一种通过Python脚本实现对大量文件按名称中特定数字进行自动分组的方法,适用于需要对文件进行快速整理的场景。

581

被折叠的 条评论
为什么被折叠?



