Python CSV编写器:编写不均匀的列

时间:2016-01-27 19:39:50

标签: python csv

我想写有不均匀列的行。以下是我的代码:

import csv
import json

path = 'E:/Thesis/thesis_get_data'
outputfile = open('maplight_113.csv', 'w', newline='')
outputwriter = csv.writer(outputfile)

with open (path + "/" + 'maplight data 113congress.json',"r") as f:
    data = json.load(f)

    for bill in data['bills']:
        b = bill.get('measure')
        for organization in bill['organizations']:
            d = organization.get('name')
            f = organization.get('disposition')
            a = (organization.get('catcode'))

            outputwriter.writerow([b, d, a, f])
            outputfile.flush();

每一个" bill.get(' measure')"在我的数据中,可能有一组或多组" d,f,a"来自" bill ['组织']"与之相关联。我希望每一套" d,f,a"在相同的" bill.get(' measure')"中填充其他列。行。

1 个答案:

答案 0 :(得分:1)

这是怎么回事?

with open (path + "/" + 'maplight data 113congress.json',"r") as f:
    data = json.load(f)

    for bill in data['bills']:
        b = bill.get('measure')
        tmp = [(x.get('name'), x.get('catcode'), x.get('disposition')) for x in bill['organizations']]
        outputwriter.writerow(chain((b), *tmp))
        outputfile.flush()

你需要:

from itertools import chain
相关问题