【问题标题】:Edit CSV file in python which reads values from another json file in python在 python 中编辑 CSV 文件,该文件从 python 中的另一个 json 文件中读取值
【发布时间】:2015-12-21 06:37:55
【问题描述】:

我想编辑一个 csv 文件,该文件从我在 python 2.7 中的另一个 json 文件中读取值 我的 csv 是:a.csv

a,b,c,d
,10,12,14
,11,14,15

我的 json 文件是 a.json

{"a":20}

我希望我的列“a”将尝试在 json 文件中匹配。如果他们是匹配的。它应该从 json 复制该值并将其粘贴到我的 csv 文件中,我的 csv 文件的最终输出应该如下所示。

a,b,c,d
20,10,12,14
20,11,14,15

到目前为止,我尝试过的是

 fileCSV = open('a.csv', 'a')

 fileJSON = open('a.json', 'r')
 jsonData = fileJSON.json()

 for k in range(jsonData):
     for i in csvRow:
        for j in jsonData.keys():
            if i == j:
               if self.count == 0:

                  self.data = jsonData[j]
                  self.count = 1
               else:

                  self.data = self.data + "," + jsonData[j]         

    self.count = 0
    fileCSV.write(self.data)
    fileCSV.write("\n")
    k += 1 
fileCSV.close()           
print("File created successfully")

如果有人能帮助我,我将非常感激。 请忽略任何语法和缩进错误。 谢谢。

【问题讨论】:

  • 您是否已经知道如何加载 JSON、打开和读取 csv 文件以及操作字符串?如果是,有什么问题?如果没有,为什么你没有发现?
  • 到目前为止有什么尝试?请显示一些代码!
  • 制作一个工作示例(可能使用StringIO 而不是文件来使其成为单个文件示例),以便我们了解您的位置。我们通常不会在这里写代码。如果我们能看到您的位置并根据需要进行调整,那就最好了。
  • 我发布了我到目前为止尝试过的代码.. 但是 stackoverflow 和社区响应非常快,在发布之前,我得到了响应。 :D

标签: python json csv


【解决方案1】:

一些基本的字符串解析会带你到这里。我写了一个脚本,它适用于你所指的简单场景。

检查这是否解决了您的问题:

import json
from collections import OrderedDict


def list_to_csv(listdat):
    csv = ""
    for val in listdat:
        csv = csv+","+str(val)
    return csv[1:]

lines = []
csvfile = "csvfile.csv"
outcsvfile = "outcsvfile.csv"
jsonfile = "jsonfile.json"

with open(csvfile, encoding='UTF-8') as a_file:
        for line in a_file:
            lines.append(line.strip())

columns = lines[0].split(",")
data = lines[1:]

whole_data = []
for row in data:
    fields = row.split(",")
    i = 0
    rowData = OrderedDict()
    for column in columns:
        rowData[columns[i]] = fields[i]
        i += 1
    whole_data.append(rowData)

with open(jsonfile) as json_file:
    jsondata = json.load(json_file)

keys = list(jsondata.keys())

for key in keys:
    value = jsondata[key]
    for each_row in whole_data:
        each_row[key] = value

with open(outcsvfile, mode='w', encoding='UTF-8') as b_file:
    b_file.write(list_to_csv(columns)+'\n')
    for row_data in whole_data:
        row_list = []
        for ecolumn in columns:
            row_list.append(row_data.get(ecolumn))
        b_file.write(list_to_csv(row_list)+'\n')

CSV 输出不会写入源文件,而是写入不同的文件。 输出文件也总是被截断和写入,因此是 'w' 模式。

【讨论】:

    【解决方案2】:

    我建议使用csv.DictReadercsv.DictWriter 类,它们将读入和读出python dicts。这样可以更轻松地修改您从 JSON 文件中读取的 dict 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 2021-06-16
      • 2020-03-29
      • 2018-01-08
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多