从CSV文件创建JSON

时间:2018-04-16 05:40:15

标签: python json csv

I have a csv file like this
RPM,Load Current,Output
1200,3,12
1500,4,13

And I have to create a json file in this format

SpikeData:{
"RPM" = [1200,1500],
"Load Current" = [3,4],
"Output" = [12,13]
}

I have written the following code to read the csv file and convert it to 
json.

import csv
import json

#Read CSV File
def read_csv():
    SpikeData={"RPM":[],"Load Current":[],"Output":[]}

    with open('power1.txt') as CSV_file_ref:
        Reader = csv.DictReader(CSV_file_ref)
        columns_of_first_line = Reader.fieldnames
        for row in Reader:
        SpikeData['RPM'].append(row[i] for i in range(len(column_of_first_line)))   
        print(SpikeData)

if __name__ == "__main__":
   read_csv()

当我打印SpikeData时,我得到输出为

    {
    'LoadCurrent': [],
    'BatteryOutput': [], 
    'PowerCapacity': [],
    'RPM': [<generator object <genexpr> at 0x0000000005B8A7E0>,
     <generator object <genexpr> at 0x0000000005BE07E0>,
     <generator object <genexpr> at 0x0000000005BE0630>]
   }

有人可以帮我解决这个问题吗。

  

我期待将价值保存在&#39; RPM&#39;喜欢&#39; RPM&#39; = [1200,1500]

但保存的值是

 'RPM': [<generator object <genexpr> at 0x0000000005B8A7E0>, 
  <generator object <genexpr> at 0x0000000005BE07E0>,
  <generator object <genexpr> at 0x0000000005BE0630>]

2 个答案:

答案 0 :(得分:0)

您需要稍微更改一下代码,不需要生成器表达式

import csv
import json

#Read CSV File
def read_csv():
    SpikeData={"RPM":[],"Load Current":[],"Output":[]}

    with open('power1.txt') as CSV_file_ref:
        Reader = csv.DictReader(CSV_file_ref)
        for row in Reader:
            SpikeData['RPM'].append(row['RPM'])
            SpikeData['Load Current'].append(row['Load Current'])
            SpikeData['Output'].append(row['Output'])
        print(SpikeData)

if __name__ == "__main__":
   read_csv()

输出:

{'Output': ['12', '13'], 'RPM': ['1200', '1500'], 'Load Current': ['3', '4']}

答案 1 :(得分:0)

#csv file content
----------------------
RPM,Load Current,Output
1200,3,12
1500,4,13
--------------------

code:

import pandas as pd
import json
df = pd.read_csv('sample.csv')
csv_file = pd.DataFrame(pd.read_csv("sample.csv", sep = ",", header = 0, index_col = False))
data = json.loads(csv_file.to_json())
print data

输出:

{"RPM":{"0":1200,"1":1500},"Load Current":{"0":3,"1":4},"Output":{"0":12,"1":13}}