Python CSV导出异常:仅需部分JSON数据却导出全部的问题排查
问题描述
我开发了一个Python程序,用Tkinter展示JSON文件中符合WarnTimeC < ErrorHours时间范围的数据,同时支持导出为CSV文件供Excel或Access处理。目前Tkinter界面展示、计数统计、打印输出都正常,但CSV导出时总是导出JSON里的全部条目:测试时JSON有10条数据,符合条件的只有5条,可CSV导出了全部10条;手动改成7条数据后,还是导出全部7条。附上相关代码,求解决CSV只导出符合条件数据的问题。
原代码
for item in data['People']: # WarnTimeC is calculated here but the code is irelevent for the problem so ive removed it # ErrorHours is gathered from an entry box if WarnTimeC < ErrorHours: CSVName = 'API_Programs/Output CSV/CSV_Output_' + str(datetime.now().strftime('%d_%m_%Y_%H_%M_%S')) + '.csv' with open(CSVName, "w", newline="") as file: csv_file = csv.writer(file) csv_file.writerow([ 'First_Name', 'Last_Name', 'City', 'Job', 'Revenue', 'Last_Update', 'API_CHECK', ]) for item in data['People']: if WarnTimeC < ErrorHours: csv_file.writerow([ item['general'].get('FName', 'N/A'), item['general'].get('LName', 'N/A'), item['specific'].get('City', 'N/A'), item['specific'].get('Job', 'N/A'), item['specific'].get('Revenue', 'N/A'), item['specific'].get('Update-time', 'N/A').replace("-","/").replace("T"," ").replace("Z",""), CALLZULU, ]) print("done") CSVcounter += 1 # sanity check prints print(ErrorHours) print(WatnTimeC) print(CSVcounter) print(dateTimeDifferenceInHours)
问题分析与解决方案
核心问题
- 嵌套循环逻辑错误:外层遍历
data['People']时,每遇到一条符合条件的条目就重新创建CSV、写入表头,再完整遍历一次所有条目——这会导致CSV被多次覆盖,且内层循环复用的是外层当前条目的WarnTimeC值,而非内层每条数据的计算值,最终导出全部数据。 - 条件判断复用错误:内层循环的
WarnTimeC未重新计算,判断条件失效,导致所有条目都被写入。
修正代码
import csv from datetime import datetime # 1. 先筛选所有符合条件的条目 filtered_data = [] # 从输入框获取ErrorHours(需转为数值类型,示例为float) ErrorHours = float(你的输入框对象.get()) for item in data['People']: # 计算当前条目的WarnTimeC(补全你的计算逻辑) # WarnTimeC = 你的时间差计算代码 if WarnTimeC < ErrorHours: filtered_data.append(item) # 2. 导出筛选后的数据到CSV if filtered_data: CSVName = f'API_Programs/Output CSV/CSV_Output_{datetime.now().strftime("%d_%m_%Y_%H_%M_%S")}.csv' with open(CSVName, "w", newline="", encoding="utf-8") as file: csv_writer = csv.writer(file) # 写入表头 csv_writer.writerow([ 'First_Name', 'Last_Name', 'City', 'Job', 'Revenue', 'Last_Update', 'API_CHECK' ]) # 写入符合条件的数据 for item in filtered_data: csv_writer.writerow([ item['general'].get('FName', 'N/A'), item['general'].get('LName', 'N/A'), item['specific'].get('City', 'N/A'), item['specific'].get('Job', 'N/A'), item['specific'].get('Revenue', 'N/A'), item['specific'].get('Update-time', 'N/A').replace("-","/").replace("T"," ").replace("Z",""), CALLZULU, ]) print("CSV导出完成") CSVcounter = len(filtered_data) # 调试输出 print(f"ErrorHours: {ErrorHours}") print(f"符合条件的条目数: {CSVcounter}") else: print("没有符合条件的数据可导出")
关键改进点
- 先统一筛选符合条件的条目,避免重复遍历和文件覆盖
- 仅创建一次CSV文件,写入一次表头和筛选后的数据
- 用
len(filtered_data)直接获取符合条件的条目数,统计更准确
内容的提问来源于stack exchange,提问作者CantCode2SaveHerself
相关产品推荐
相关产品推荐

