csv转json--中文操作等

转载至:https://zhuanlan.zhihu.com/p/52389842

csv 文件转json文件

import sys
import json

input_file = sys.argv[1]
lines = ""
# 读取文件
with open(input_file, "r",encoding='utf-8') as f:
    lines = f.readlines()
lines = [line.strip() for line in lines]
keys = lines[0].split(',') 
line_num = 1
total_lines = len(lines)
# 数据存储
datas = []
while line_num < total_lines:
        values = lines[line_num].split(",")
        datas.append(dict(zip(keys, values)))
        line_num = line_num + 1
# 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
json_str = json.dumps(datas, ensure_ascii=False, indent=4)
# 去除\",\\N,\n 无关符号
result_data = json_str.replace(r'\"','').replace(r'\\N','').replace(r'\n','')
output_file = input_file.replace("csv", "json")
# 写入文件
with open(output_file, "w", encoding="utf-8") as f:
    f.write(result_data)
    print("convert success")

运行

$ python csv_to_json.py index.csv 控制台输出 convert success 表示带出成功

效果
index.json
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值