这篇“Python如何实现自动整理表格”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python如何实现自动整理表格”文章吧。
原理
第一步,遍历文件夹下的所有文件和子文件夹的名称,并获取子文件夹下的文件的年份信息和数量信息
第二步,将年份信息进行格式化,连续的年份取最小值和最大值,并用“-”连接,单独的年份单独提取出,并用顿号连接
第三步,写入数据到Excel中
目标实现
遍历文件,新建数据存放的List
path=os.getcwd() file_list=list(os.walk(path)) infomation=[] yearList=[]
获取信息
 if '/' in path:
  infomation.append(file_list[i][0].replace(path+'/',''))
 elif '' in path:
  infomation.append(file_list[i][0].replace(path+'',''))
 totalNum=len(file_list[i][2])
 for j in range (0,len(file_list[i][2])):
  year=re.findall(r'd{4}',file_list[i][2][j])
  yearList.append(int(year[0]))
 yearList.sort()年份信息格式化
for i in range(len(yearList)): if not res: res.append([yearList[i]]) elif yearList[i-1]+1==yearList[i]: res[-1].append(yearList[i]) else: res.append([yearList[i]]) y=[] for m in range (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=[]最终的完整代码如下
import os
import re
from openpyxl import load_workbook
wb=load_workbook('表格.xlsx')
ws=wb.active
path=os.getcwd()
file_list=list(os.walk(path))
infomation=[]
yearList=[]
for i in range (1,len(file_list)):
 if '/' in path:
  infomation.append(file_list[i][0].replace(path+'/',''))
 elif '' in path:
  infomation.append(file_list[i][0].replace(path+'',''))
 totalNum=len(file_list[i][2])
 for j in range (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=[]
 for i in range(len(yearList)):
  if not res:
   res.append([yearList[i]])
  elif yearList[i-1]+1==yearList[i]:
   res[-1].append(yearList[i])
  else:
   res.append([yearList[i]])
 y=[]
 for m in range (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=[]运行效果