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

json_result.txt
