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)) parsed_datas.append(dict(zip(keys, values))) line_num += 1 json_str = json.dumps(parsed_datas, ensure_ascii=False, indent=5) 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
16进制string转化为int
int–>string
1、int转化为10进制string
2、int转化为16进制string