在有的时候在写完代码时,可能之前能跑的文件突然error了,这时若需要对新代码进行测试,则需要保存原来的代码运行结果为excel文件,再通过新代码对同一文件夹生成相通的excel表格,依次来比较两张表格中哪些地方改变
此处代码运行结果已经存为json文件,其为一个列表[{key:value}]
import os
import json
import pandas as pd
#创建文件夹
result_df = pd.DateFrame(columns = ['name1','age','date']
folder = your_fold_path
#读取子文件夹
subfolders = [f for f in os.listdir(folder) if os.path.isdir(os.path.join(folder,f) ]
for fold in subfolders:
fold_path = os.path.join(folder,fold)
json_files = [f for f in os.listdir(fold_path) if f.endswith('.json')]
for json_file in json_files:
json_file_path = os.path.join(folder_path,json_file)
with open(json_file_path,'r',encoding = 'uff-8') as file:
json_str = file.read()
json_content = json.loads(json_str)
for item in json_content:
value1 = item['name']
value2 = item['age']
value3 = item['date']
#将数据存为df形式
result_df = result_df.append({'文件名':fold,'name':value1,'age':value2,'date':value3})
#将df转为excel
result_excel_file = r'希望保存的路径'
result_df.to_excel(result_excel_file,index=False)
此时得到老版本代码产生数据的内容并将其存为excel,更新代码后依然使用此代码对旧数据产生新的excel,然后通过以下compare函数来对比差异
file_path = r'文件一'
file_path = r'文件二'
df = pd.read_excel(file_path)
df1 = pd.read_excel(filepath1)
column_A='name'
column_B = 'age'
column_C = 'date'
column_D = '文件名‘
#首先判断文件是否都被读取,采用集合set很方便
set_file_name = set(df[column_D])
set_file_name1 = set(df1[column_D])
#多读取的文件:
added_file_name = set_file_name1 - set_file_name
#没读到的文件
miss_file_name = set_file_name - set_file_name1
#正确读取的文件
correct_file_name = set_file_name&set_file_name1
#打印这些
for add in add_file_name:
print('多读的文件:',add)
for miss in miss)file)name:
print('漏读的文件:’,miss
#当文件都被正确读取时,再去比较文件中的其他属性是否正确
error_date=[]
error_name=[]
error_age = []
for idx ,filename in enumerate(df[column_D])
for idx1,filename1 in enumerate(df[column_D])
if filename = filename1:
if df[colum_B].loc[idx]!= df1[column_B].loc[idx1]
print('读取到错误年龄:',str(filename)+':'+str(df1[column_B].loc[idx1]))
if df[colum_C].loc[idx]!= df1[column_C].loc[idx1]
print('读取到错误日期:',str(filename)+':'+str(df1[column_C].loc[idx1]))
if df[colum_A].loc[idx]!= df1[column_A].loc[idx1]
print('读取到错误名称:',str(filename)+':'+str(df1[column_A].loc[idx1]))
print('比较完毕')
完成比较