python将CSV文件转换成JSON格式的文件

本文详细介绍如何使用Python将CSV文件转换为JSON格式,包括利用JSON参数美化输出、处理中文编码及利用OS模块操作文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON参数介绍:
"""
ensure_ascii=False 中文编码问题
sort_keys=False  将数据根据keys的值进行排序
indent=4 应该是一个非负的整型,如果是0,或者为空,则一行显示数据,否则会换行且
按照indent的数量显示前面的空白,这样打印出来的json数据也叫pretty-printed json
separators=(',', ': ') 分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);
这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开
"""

OS模块介绍:

"""

json_file_result='D:/img/json_result.txt'

获取文件的绝对路径

os.path.abspath(json_file_result)

json_file_result='D:/img/json_result.txt'
os.path.abspath(json_file_result)
'D:\\img\\json_result.txt'

判断文件是否存在:

os.path.exists(json_file_result)

存在:True 不存在:Fa在:False

os.path.exists(json_file_result)
True

 

"""

以下代码是将csv文件的内容处理成JSON格式的文本(“2.csv”处理成“json_result.txt”)

代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'abel
__mtime__ = '2019/7/30'
"""
import json,os,re

source_file='D:/img/2.csv'
json_file_result='D:/img/json_result.txt'
zd_key = ["userCode", "stbId", "name", "mobile", "status", "thirdUserId"]
#判断文件是否存在,并清空文件内容
if os.path.exists(json_file_result):
	with open(json_file_result,"r+") as f:
		f.truncate()
if os.path.isfile(source_file):
	#处理CSV文件,将文件里的内容取出来,并组装成一个列表
	with open(source_file,'r',encoding='UTF-8') as f:
		lines=f.readlines()
		for i in lines:
            #去掉首行内容(标题)
			ifalerm=re.search('房间号',i)
			if not ifalerm:
				l=i.strip("\n").split(",")
                #将CSV里的内容作为字典的value,zd_k列表的内容作为字典的key
				zd = dict(zip(zd_key, l))
				data_json = json.dumps(zd, ensure_ascii=False, sort_keys=False, indent=4,
									   separators=(',', ': '))
                #将JSON格式的数据存储到txt文件中,便于使用
				with open(json_file_result,'a+',encoding='utf-8') as f:
					f.write(data_json + '\n,\n')
					f.close()

	print("写入完成。。。。。","\n""文件路径是:%s"%(os.path.abspath(json_file_result)))
else:
	print("文件不存在。。。。")

2.csv

2.csv

json_result.txt

json_result.txt
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abel_dwh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值