CSV文件转JSON

例子一: 利用json库转换CSV文件

首先我的csv文件长成这样,其中第一行与第二行分别是边的两侧结点

236 186
122 285
24 346
271 304
176 9
130 329
204 213

目的json文件应该为这样

1
2
3
4
5
6
"links":[
{
"id": "0",
"source": "236",
"target": "186"
},

注意:”links” 是我手动添加的,正常生成我现在也不知道该如何添加到此块内容

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import json
input_file = './0dges.csv'
lines = open(input_file,"r").readline() #读取文件的行
lines = [line.strip()] for line in lines 对于每一行通过空格进行分割
keys = ['id','source','target'] # 字典
line_num = 0
total_lines = len(lines) #字的长度
parsed_datas = []
while line_num < total_lines:
values = lines[line_num].split(",") # 根据,号进行分割
values.insert(0,str(line_num)) #str转字符型,也就是在这个list前添加一个字符为行号的数字
parsed_datas.append(dict(zip(keys, values))) #dict 是字典每一行都添加一定的内容,映射加迭代的方式
line_num += 1
json_str = json.dumps(parsed_datas, ensure_ascii=False, indent=5) # dumps 转换成json数据类型,ensure_ascii 是防止中文乱码,indent 为格式化输出
output_file = input_file.replace("csv", "json") # 字符串替代函数
output = './test_json1.json'
f = open(output, "w", encoding="utf-8")
f.write(json_str)
f.close()

涉及到的小知识点

1.dict 字典函数的具体应用

1
2
3
4
5
6
7
8
9
>>>dict()                        # 创建空字典
{}
>>> dict(a='a', b='b', t='t') # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>>

2.open(“”,””)函数中,第一参数是文件名,第二个参数便是可读或者可写,r为读,w为写

3.[]后面同样需要”,”号

进制转换,字符串与整型内容的变换

string–>int

10进制string转化为int

1
 int('12')

16进制string转化为int

1
 int('12', 16)

int–>string

1、int转化为10进制string

1
 str(18)

2、int转化为16进制string

1
 hex(18)