def write_json_cjb_last_month(csv_file_path):
last_cjb = {}
with open(csv_file_path, 'r') as f:
rows = csv.reader(f)
header = next(rows)
结算账号_index = header.index('结算账号-CMDM')
地区_index = header.index('结算归属地区.1')
小组_index = header.index('小组')
应收金额_index = header.index('应收金额')
for row in rows:
结算账号 = row[结算账号_index]
应收金额 = float(row[应收金额_index]) if row[应收金额_index].strip() else 0 # 转换为数字并处理空值
if 结算账号 in last_cjb:
# 如果结算账号已存在,累加应收金额
last_cjb[结算账号]["应收金额"] = str(float(last_cjb[结算账号]["应收金额"]) + 应收金额)
else:
# 如果是新的结算账号,创建新记录
last_cjb[结算账号] = {
"地区": row[地区_index],
"小组": row[小组_index],
"应收金额": str(应收金额)
}
with open('json数据/data.json', 'w', encoding='utf-8') as f:
json.dump(last_cjb, f, ensure_ascii=False, indent=4)
write_json_cjb_last_month(csv_file_path)
4、代码2---全字段
python复制代码
def csv_to_json(csv_file_path):
with open(csv_file_path, 'r',encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader)
data = [dict(zip(header, row)) for row in reader]
with open('data.json', 'w',encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
csv_to_json(file_name)
5、代码3---全字段
python复制代码
def csv_to_json(csv_file_path, json_file_path):
# 使用 DictReader 直接将每一行解析为字典
with open(csv_file_path, mode='r', encoding='utf-8', newline='') as csvfile:
reader = csv.DictReader(csvfile)
# 打开 JSON 文件,并分块写入
with open(json_file_path, mode='w', encoding='utf-8') as jsonfile:
# 增加 JSON 数组的开头
jsonfile.write('[')
first_line = True
for row in reader:
# 分块写入 JSON,避免一次性将所有数据加载进内存
if not first_line:
jsonfile.write(',\n')
json.dump(row, jsonfile, ensure_ascii=False)
first_line = False
# 结束 JSON 数组
jsonfile.write('\n]')
# 执行 CSV 转 JSON 的操作
csv_to_json(file_name, json_file)
# 读取生成的 JSON 文件进行验证
with open(json_file, mode='r', encoding='utf-8') as f:
data = json.load(f)
for i in data:
print(i)