【问题标题】:Not getting expected output in python when converting a csv to json将 csv 转换为 json 时在 python 中没有得到预期的输出
【发布时间】:2018-10-02 13:08:39
【问题描述】:

我有一个 excel 文件,其中数据以 csv 格式以这种方式保存。该数据存在于 excel 文件中,如下所示,在 A 列下(CSV 文件由我编写的 LabView 软件代码生成生成数据)。我还在我的问题末尾附上了 csv 文件的图像以供参考。

RPM,Load Current,Battery Output,Power Capacity
1200,30,12,37
1600,88,18,55

我想创建一个这种格式的 Json 文件

{  
   "power_capacity_data" :
   {
   "rpm" : ["1200","1600"],
   "load_curr" : ["30","88"],
   "batt_output" : ["12","18"],
   "power_cap" : ["37","55"]
   }
 }

这是我的代码

import csv
import json 

def main():

    #created a dictionary so that i can append data to it afterwards

    power_data = {"rpm":[],"load_curr":[],"batt_output":[],"power_cap":[]}

    with open('power1.lvm') as f:
        reader = csv.reader(f)

        #trying to append the data of column "RPM" to dictionary
       rowcount = 0
       for row in reader:   
           if rowcount == 0:
               #trying to skip the first row
               rowcount = rowcount + 1 
           else:
               power_data['rpm'].append(row[0])
               print(row)

        json_report = {}        
        json_report['pwr_capacity_data'] = power_data
        with open('LVMJSON', "w") as f1:
            f1.write(json.dumps(json_report, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
            f1.close()


 if __name__ == "__main__":
     main()

我得到的输出 json 文件是这样的:(请忽略我代码中的 print(row) 语句)

{
"pwr_capacity_data": 
  {
    "load_curr": [],
    "rpm": [
        "1200,30,12.62,37.88",
        "1600,88,18.62,55.88"
    ],
    "batt_output": [],
    "power_cap": []
  } 
}

整行都保存在列表中,但我只想保存 RPM 列下的值。有人可以帮我解决我可能做错的事情吗。提前致谢。I have attached an image of csv file to just in case it helps

【问题讨论】:

    标签: python json csv reader


    【解决方案1】:

    您可以使用 Python 的 defaultdict 使其更容易一些。也是一个映射所有标题值的字典。

    from collections import defaultdict    
    import csv
    import json
    
    power_data = defaultdict(list)
    
    header_mappings = {
        'RPM' : 'rpm',
        'Load Current' : 'load_curr',
        'Battery Output' : 'batt_output',
        'Power Capacity' : 'power_cap'}
    
    with open('power1.lvm', newline='') as f_input:
        csv_input = csv.DictReader(f_input)
    
        for row in csv_input:
            for key, value in row.items():
                power_data[header_mappings[key]].append(value)
    
    with open('LVMJSON.json', 'w') as f_output:            
        json.dump({'power_capacity_data' : power_data}, f_output, indent=2)
    

    给你一个输出 JSON 文件,如下所示:

    {
      "power_capacity_data": {
        "batt_output": [
          "12",
          "18"
        ],
        "power_cap": [
          "37",
          "55"
        ],
        "load_curr": [
          "30",
          "88"
        ],
        "rpm": [
          "1200",
          "1600"
        ]
      }
    }
    

    【讨论】:

    • 嗨@Martin,感谢您的建议,我一定会尝试的。我对我的实现还有一个疑问。我正在读取的 csv 文件中的所有数据都保存在 A 列下(您可以在我的问题中提供的链接中看到附加的图像)。您认为这是原因吗在我的输出中,我得到了整行而不是行中的单个值。
    • 如果您的数据显示在一列中,它肯定不会正确加载。我假设您的数据与您在问题顶部的 CSV 文本格式一样。也许使用pastebin 之类的服务来发布指向实际文件的链接。
    猜你喜欢
    • 2015-04-29
    • 2020-09-01
    • 1970-01-01
    • 2019-12-13
    • 2015-10-14
    • 2017-01-30
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多