csv writer,将列表项添加到行尾

时间:2017-05-26 02:37:42

标签: python json python-3.x csv

我试图解析一堆数据来自动生成此报告。除了JSON数据每个项目都有一个标签列表之外,我主要使用它。它们嵌套在每个"任务项"。

我希望csv看起来像这样

Name,Title,Description,Priority,Tag1, Tag2, Tag3, Tag4

以下代码有效,因为json数据中的标记嵌套为

tags: [
{
id: 56131,
name: "NotNeeded",
color: "#a6a6a6"
},
{
id: 60598,
name: "Other",
color: "#f47fbe"
},
{
id: 60493,
name: "Test",
color: "#2f8de4"
}

我只想要标签,而不是剩下的东西。我想在每一行的末尾添加每个标记。有些有三个标签,有些有一个等等。我现在只是想让它们写,但是使用这个代码,它们都会在第1列的新行上打印。

除此之外,我还想构建一个if语句,以确定它所属的标记标题......如if name = "Other" put under header Tag3

with open('test.csv', 'w', newline='') as csvfile:
 csvwriter = csv.writer(csvfile, lineterminator='\n')
 csvwriter.writerow(["Name", "Title", "Description", "priority", "tags"])
 for each in jdata['todo-items']:
  csvwriter.writerow([(each["todo-list-name"]),
   (each["content"]),
   (each["description"]),
   (each["priority"])])
  for tags in each['tags']:
   csvwriter.writerow([(tags["name"])])

编辑:目前为止我的工作方式是有效的(除了标签在输出中有['标记']。

with open('test.csv', 'w', newline='') as csvfile:
 csvwriter = csv.writer(csvfile, lineterminator='\n')
 csvwriter.writerow(["Name", "Title", "Description", "priority", "tags"])

 for each in jdata['todo-items']:
  write_list = [(each["todo-list-name"]),
   (each["content"]),
   (each["description"]),
   (each["priority"])]
  for tags in each['tags']:
   write_list.append([(tags["name"])])
  csvwriter.writerow(write_list)

2 个答案:

答案 0 :(得分:0)

在写出之前构建列表。

with open('test.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, lineterminator='\n')
    csvwriter.writerow(["Name", "Title", "Description", "priority", "tags"])

    for each in jdata['todo-items']:
        write_list = [(each["todo-list-name"]),
                      (each["content"]),
                      (each["description"]),
                      (each["priority"])]

    for tags in each['tags']:
        write_list.append(tags["name"])

    csvwriter.writerow(write_list)

答案 1 :(得分:0)

嵌套第二个for循环并在写入之前将其添加到列表中。 谢谢@Seanny的帮助。

with open('test.csv', 'w', newline='') as csvfile:
 csvwriter = csv.writer(csvfile, lineterminator='\n')
 csvwriter.writerow(["Name", "Title", "Description", "priority", "tags"])

 for each in jdata['todo-items']:
  write_list = [(each["todo-list-name"]),
   (each["content"]),
   (each["description"]),
   (each["priority"])]
  for tags in each['tags']:
   write_list.append([(tags["name"])])
  csvwriter.writerow(write_list)