2016-01-27 130 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:預期的序列 –