2016-01-27 95 views
0

我想写入具有不均匀列的行。下面是我的代码: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(‘测量’)”在我的数据,可能有“d,F,A”,从“账单[组织']”的一组或多组与之相关联。我希望每一组“d,f,a”在同一个“bill.get('measure')”行中填写其他列。

+0

您可以将列表()'更多的数据,如果需要分配给一个变量,然后用户梅托德'.append到列表中。 – Trimax

回答

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 
+0

谢谢帕维尔, 我试过了,得到这个错误: 回溯(最近最后调用最后一次): 文件“E:/ Thesis/thesis_get_data/code for parsing maplight senate data part 2 .py”,in line 18,in在bill ['organizations']))中的x outputwriter.writerow(chain((b,x.get('name'),x.get('catcode'),x.get('disposition'))) _csv.Error:期望的序列 –

+0

现在应该更好 –

+0

仍然有点麻烦: 回溯(最近最后调用最后一次): 文件“E:\ Thesis \ thesis_get_data \ code for parsing maplight senate data part 2 .py”,line 19,在 outputwriter.writerow(chain((b),* tmp)) _csv.Error:预期的序列 –