Python如何实现自动整理表格
导读:本文共1676.5字符,通常情况下阅读需要6分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 原理第一步,遍历文件夹下的所有文件和子文件夹的名称,并获取子文件夹下的文件的年份信息和数量信息第二步,将年份信息进行格式化,连续的年份取最小值和最大值,并用“-”连接,单独的年份单独提取出,并用顿号连接第三步,写入数据到Excel中目标实现遍历文件,新建数据存放的Listpath=os.getcwd()file_list=list(os.walk(path))... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。原理
第一步,遍历文件夹下的所有文件和子文件夹的名称,并获取子文件夹下的文件的年份信息和数量信息
第二步,将年份信息进行格式化,连续的年份取最小值和最大值,并用“-”连接,单独的年份单独提取出,并用顿号连接
第三步,写入数据到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=[]
运行效果
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
Python如何实现自动整理表格的详细内容,希望对您有所帮助,信息来源于网络。