目录
专栏导读
🌸 欢迎来到Python办公自动化专栏---Python处理办公问题,解放您的双手
🏳️🌈 博客主页:请点击------> 一晌小贪欢的博客主页求关注
👍 该系列文章专栏:请点击------>Python办公自动化专栏求订阅
🕷 此外还有爬虫专栏:请点击------>Python爬虫基础专栏求订阅
📕 此外还有python基础专栏:请点击------>Python基础学习专栏求订阅
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
❤️ 欢迎各位佬关注! ❤️
1、背景
我们有时候经常会将csv文件转为json数据(本地),然后加载json数据作为匹配项,可以将里面的数据匹配给其他的表格中
2、库的安装
库 | 用途 | 安装 |
---|---|---|
无需安装 | 无需安装 | 无需安装 |
3、代码1---自定义表头
数字类型可累加
python
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)