python - Converting a CSV file into a JSON file using python
问题描述
I have been trying to convert a csv file into json with python 3. I want to convert a csv file which would look more or less like this:
Key ,Field_1 ,Field_2 ...
0 ,a ,e ...
1 ,b ,f ...
2 ,c ,g ...
3 ,d ,h ...
Into a json file that is structured Key : [Field_1, Field_2, ...]
So that the csv above would end up looking like
{
"0" : ["a", "e", ...]
"1" : ["b", "f", ...]
"2" : ["c", "g", ...]
"3" : ["d", "h", ...]
}
I have been trying to use the code below but have been unable to fill in the missing parts, like assigning each value to their corresponding part on the json file.
csv = pd.read_csv("file.csv")
n = 0
length = # number of keys
for i in csv:
if n == 0:
for y in range(lentgh):
# Assign as the header
else:
for y in range(length):
# Assign as the properties
n += 1
Also Im trying to make it so that all new data is attached at the end of the json file automatically.
解决方案
仍然会json
缩进值列表,但这会将您的 csv 转换为您想要的字典并将其附加到 json 文件
import csv
import json
with open('blah.csv') as f:
reader = csv.reader(f)
next(reader)
d = dict((rows[0], rows[1:]) for rows in reader)
with open('blah.json', 'a') as f:
json.dump(d, f, indent=4)
推荐阅读
- http - 在 HoloLens 上渲染图像时出现延迟
- azure-devops - 合并 PR 后如何限制 Azure DevOps YAML 管道中的关联工作项?
- python - 用 print 包围一个函数(返回密码)后,为什么该函数不能重复?
- html - 如何在 CSS 中的图标和文本之间留出空格
- kubernetes - 为什么使用 istio 时 https 请求正确返回但 http 请求返回不正确?
- java - JGraphT 中是否有类似 networkx 中的 k_edge_components() 的函数
- python - 在 multiprocessing 和不使用 multiprocessing.Pool 之间切换的简单方法?
- laravel - 将控制器中的数据字段用于另一个 crud
- java - 异常处理执行流程
- python - 如何在具有 numpy 数组的列的数据框中删除重复项?