Python如何实现自动整理表格(python,开发技术)

时间:2024-04-29 14:18:35 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

原理

第一步,遍历文件夹下的所有文件和子文件夹的名称,并获取子文件夹下的文件的年份信息和数量信息

第二步,将年份信息进行格式化,连续的年份取最小值和最大值,并用“-”连接,单独的年份单独提取出,并用顿号连接

第三步,写入数据到Excel中

目标实现

遍历文件,新建数据存放的List

path=os.getcwd()file_list=list(os.walk(path))infomation=[]yearList=[]

获取信息

if'/'inpath:infomation.append(file_list[i][0].replace(path+'/',''))elif'\\'inpath:infomation.append(file_list[i][0].replace(path+'\\',''))totalNum=len(file_list[i][2])forjinrange(0,len(file_list[i][2])):year=re.findall(r'\d{4}',file_list[i][2][j])yearList.append(int(year[0]))yearList.sort()

年份信息格式化

foriinrange(len(yearList)):ifnotres:res.append([yearList[i]])elifyearList[i-1]+1==yearList[i]:res[-1].append(yearList[i])else:res.append([yearList[i]])y=[]forminrange(0,len(res)):if(max(res[m])==min(res[m])):y.append(str(max(res[m])))else:y.append(str(min(res[m]))+'-'+str(max(res[m])))yearInfo="、".join(y)

保存数据并输出到Excel中

infomation.append(yearInfo)infomation.append(totalNum)print(infomation)ws.append(infomation)wb.save('表格.xlsx')infomation=[]yearList=[]

最终的完整代码如下

importosimportrefromopenpyxlimportload_workbookwb=load_workbook('表格.xlsx')ws=wb.activepath=os.getcwd()file_list=list(os.walk(path))infomation=[]yearList=[]foriinrange(1,len(file_list)):if'/'inpath:infomation.append(file_list[i][0].replace(path+'/',''))elif'\\'inpath:infomation.append(file_list[i][0].replace(path+'\\',''))totalNum=len(file_list[i][2])forjinrange(0,len(file_list[i][2])):year=re.findall(r'\d{4}',file_list[i][2][j])yearList.append(int(year[0]))yearList.sort()res=[]foriinrange(len(yearList)):ifnotres:res.append([yearList[i]])elifyearList[i-1]+1==yearList[i]:res[-1].append(yearList[i])else:res.append([yearList[i]])y=[]forminrange(0,len(res)):if(max(res[m])==min(res[m])):y.append(str(max(res[m])))else:y.append(str(min(res[m]))+'-'+str(max(res[m])))yearInfo="、".join(y)infomation.append(yearInfo)infomation.append(totalNum)print(infomation)ws.append(infomation)wb.save('表格.xlsx')infomation=[]yearList=[]

运行效果

Python如何实现自动整理表格

Python如何实现自动整理表格

Python如何实现自动整理表格

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Python如何实现自动整理表格的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:webpack5新特性Asset Modules资源模块怎么用下一篇:

8 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18