一、大量文件名读取与入表
- 业务需求:把207张Excel表的文件名与表中的某个字段数据合成一张表
步骤:
- 首先,通过递归把207张表的文件名遍历出来
- 把遍历出来的文件名存储到列表中
- 通过Pandas模块中的read_excel()函数把对应的字段存储到列表中
- 难点:解决一个文件名对应多条数据,此时该文件名重复的问题?

代码实现如下:
import osimport pandasimport pandas as pdfrom pandas import read_exceldef show_files(path, all_files):# 首先遍历当前目录所有文件及文件夹file_list = os.listdir(path)# 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归for file in file_list:# 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录cur_path = os.path.join(path, file)# 判断是否是文件夹if os.path.isdir(cur_path):show_files(cur_path, all_files)else:all_files.append(file)return all_files"""oldpath:文件的源路径;new_file_name:生成的最新的文件;"""def to_excel_num(oldpath,new_file_name):contents = show_files(oldpath, [])#所有文件的文件名列表;list_num = []new_df = []new_df2 = []# 循环打印show_files函数返回的文件名列表for content in contents:df = read_excel(str(oldpath)+str(content))for k in range(0,int(len(df))):list_num.append(content.split('.')[0])for v in df.values.tolist():new_df.append(v[1])new_df2.append(v[1])df = pd.DataFrame({"文件名": list_num,"number":new_df2,# '好友ID': new_df})write = pd.ExcelWriter(new_file_name)df.to_excel(write,index=False)write.save()oldpath = "./files/"new_file_name = "./new_file_two.xlsx"to_excel_num(oldpath, new_file_name)
二、Excel单元格复杂数据清洗
- 业务需求:把1张Excel表的json格式字段,分解成有规则的数据,并生成一张新的Excel表
步骤:
- 首选,获取到json格式字段的列值存于列表中
- 去掉两边的{与},并以逗号隔开
- 留下表中的二个字段,并写入新的Excel表中
- 难点:解决一个字段对应多条数据,此时字段重复的问题?
原表:

实现效果:

代码实现如下:
from pandas import read_excelimport pandas as pd"""file_name参数的值表示要修改的文件;new_file_name参数的值表示生成的新文件地址"""def test_ip(file_name,new_file_name):df = read_excel(file_name)list_users = df['USERNAME'].values.tolist() #获取到USERS列的值;list_ip = df['IP'].values.tolist() #获取到IP列的值;list_users_len = [] #装users列的长度,方便后面重复;new_list_users = [] #把所有的值放到这;for v in list_users:vv = v.lstrip("{")vv = vv.rstrip("}")new_list = vv.split(",")list_users_len.append(len(new_list))for k in new_list:new_list_users.append(k)#开始对ip值重复的数量进行一一对应;new_list_ip = []len_ip = len(list_ip)for k in range(0,len_ip):for kk in range(0,list_users_len[k]):new_list_ip.append(list_ip[k])#装入数据框中;new_df = pd.DataFrame({"IP": new_list_ip,"USERNAME":new_list_users})write = pd.ExcelWriter(new_file_name)new_df.to_excel(write,index=False)write.save()#下面是调用以上函数的参数file_name = "./meiya_02.xlsx"new_file_name = "./new_file_two.xlsx"test_ip(file_name,new_file_name)
