【问题标题】:Convering json to csv using Python使用 Python 将 json 转换为 csv
【发布时间】:2019-07-18 06:23:27
【问题描述】:

我想我想做的很简单。我正在将 .json 转换为 .csv 文件,但很难得到我想要的。我确定我很傻,但在这个网站上找不到答案。请指出我的愚蠢错误是什么!

我正在使用以下 Python 代码:

import csv, json

inputFile = open('results_20190214b.txt') outputFile = open('results_20190214.csv', 'w', newline='')

data = json.load(inputFile) inputFile.close

output = csv.writer(outputFile)

for row in data:
    output.writerow([row])

outputFile.close()

我的 json 看起来像这样:

 {
                "AccumulatedNewCapacity[UTOPIA,E01,1999]": {
                    "Value": 0.0225798659394097
                },
                "AccumulatedNewCapacity[UTOPIA,E01,2000]": {
                    "Value": 0.149302162579271
                },
                "AccumulatedNewCapacity[UTOPIA,E01,2001]": {
                    "Value": 0.354595177554284
                },
                "AccumulatedNewCapacity[UTOPIA,E01,2002]": {
                    "Value": 0.553976916527268
                },
                "AccumulatedNewCapacity[UTOPIA,E01,2003]": {
                    "Value": 0.749394931502283
                }, ETC

此代码已成功将字段名称打印到 CSV,但我没有得到任何值。例如:

AccumulatedNewCapacity[UTOPIA,E01,1999]
AccumulatedNewCapacity[UTOPIA,E01,2000]
AccumulatedNewCapacity[UTOPIA,E01,2001]

非常感谢任何想法。谢谢!

【问题讨论】:

    标签: python json csv


    【解决方案1】:

    试试这个:

    import csv 
    with open('results_20190214b.txt', 'r') as in_file:
        stripped = (line.strip() for line in in_file)
        lines = (line.split(",") for line in stripped if line)
        with open('results_20190214.csv', 'w') as out_file:
            writer = csv.writer(out_file)
            writer.writerow(( 'title', 'intro')) # here enter your rows titles
            writer.writerows(lines)
    

    【讨论】:

      【解决方案2】:

      您需要迭代行,因为它也在此处描述; https://stackoverflow.com/a/26660785/11110555

      因此,您可以执行以下操作

      for row in data.items():
          output.writerow(row)
      

      但是,请记住,您最终会得到类似于 CSV 上的以下结果的元组;

      "AccumulatedNewCapacity[UTOPIA,E01,1999]",{'Value': 0.0225798659394097}
      "AccumulatedNewCapacity[UTOPIA,E01,2000]",{'Value': 0.149302162579271}
      "AccumulatedNewCapacity[UTOPIA,E01,2001]",{'Value': 0.354595177554284}
      "AccumulatedNewCapacity[UTOPIA,E01,2002]",{'Value': 0.553976916527268}
      "AccumulatedNewCapacity[UTOPIA,E01,2003]",{'Value': 0.749394931502283}
      

      我想你只想在 AccumulatedNewCapacity 和 Value to CSV 的边界中加入一部分

      for row in data.items():
          # Getting the first part of AccumulatedNewCapacity
          basePart = row[0]
          #Extracting text inside borders
          baseStr = basePart[basePart.find("[")+1:basePart.find("]")]
      
          # Getting the Value part
          valuePart = row[1]
          #Extracting value
          valueStr = valuePart['Value']
      
          output.writerow([baseStr,valueStr])
      

      这将导致您在 CSV 上获得以下结果,因为它是作为字符串而不是列表编写的。

      "UTOPIA,E01,1999",0.0225798659394097
      "UTOPIA,E01,2000",0.149302162579271
      "UTOPIA,E01,2001",0.354595177554284
      "UTOPIA,E01,2002",0.553976916527268
      "UTOPIA,E01,2003",0.749394931502283
      

      因此,您需要将值转换为列表并将值附加到其中。

      import csv, json
      
      inputFile = open('results.txt')
      outputFile = open('results_20190214.csv', 'w', newline='\n')
      
      data = json.load(inputFile)
      inputFile.close
      
      output = csv.writer(outputFile)
      
      for row in data.items():
          # Getting the first part of AccumulatedNewCapacity
          basePart = row[0]
          # Extracting text inside borders
          baseStr = basePart[basePart.find("[")+1:basePart.find("]")]
      
          # Splitting values with comma and turning into list
          writeStr = baseStr.split(",")
          # Getting the Value part
          valuePart = row[1]
          #Extracting value
          valueStr = valuePart['Value']
      
          # Adding value to the list
          writeStr.append(valueStr)
      
          # Writing into CSV
          output.writerow(writeStr)
      
      outputFile.close()
      

      编辑:忘记添加结果。结果如下所示

      UTOPIA,E01,1999,0.0225798659394097
      UTOPIA,E01,2000,0.149302162579271
      UTOPIA,E01,2001,0.354595177554284
      UTOPIA,E01,2002,0.553976916527268
      UTOPIA,E01,2003,0.749394931502283
      

      【讨论】:

        【解决方案3】:

        感谢您的回复 - 非常有帮助。

        我实际上也想将变量名称保留在 csv 中,因此最终得到了 Koray B 建议代码的轻微变体:

        for row in data.items():
            variablePart = row[0]
            variableStr = variablePart[:variablePart.find("[")]
            writeStr = []
            writeStr.append(variableStr)
            variableIndexStr = variablePart[variablePart.find("[")+1:variablePart.find("]")]
            variableIndexStrSplit = variableIndexStr.split(",")
            for i in variableIndexStrSplit:
                indexStr = i
                writeStr.append(indexStr)
        
            valuePart = row[1]
            valueStr = valuePart['Value']
            writeStr.append(valueStr)
        
            output.writerow(writeStr)
        

        【讨论】:

          猜你喜欢
          • 2018-01-04
          • 2019-02-23
          • 2021-09-01
          • 2021-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多