JSON解析不能正确循环到CSV

时间:2016-07-22 19:12:36

标签: python json csv

嗨所以我试图解析一个api的输出,但它只打印出1行,我有多行。任何人都可以帮助我为什么我的循环不工作并提供快速解决方法?

import urllib2
import csv
import json
import io
import codecs
import time

with open('/home/local/testpy2.csv',
          'rb') as csvinput:
    #output='testing1.csv'
    #writer=csv.writer(open(output,'w'))
    #headers =[address1]
    #wrtier.writerow(headers)
    reader = csv.reader(csvinput, delimiter=',')
    firstline = True
    for row in reader:
        if firstline:
            firstline = False
            continue

        address1 = row[0]
        #print row[0]
        locality = row[1]
        admin_area = row[2]
        query = ' '.join(str(x) for x in (address1, locality, admin_area))
        normalized = query.replace(" ", "+")
        BaseURL = 'http://localhost:8081/verify?country=MEX&freeform='
        URL = BaseURL + normalized
        #print URL
        data = urllib2.urlopen(URL)
        response = data.getcode()
    time.sleep(2)
    print response

        if response == 200:
            file= json.load(data)
        #print file

        output_f=open('output2.csv','wb')
        writer=csv.writer(output_f)
        header=['address1','address2','address3','address4','address5','verification_status','max_address_precision','adminstrative_area','thoroughfare']
        writer.writerow(header)     
            #count = 0
    for f in file:
        row=[]
        try:
                row.append(str(f['address1'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['address2'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['address3'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['address4'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['address5'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['analysis']['verification_status'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['analysis']['address_precision'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['analysis']['max_address_precision'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['components']['administrative_area'].encode('utf-8')))
        except:
                row.append('')
        try:
                row.append(str(f['components']['thoroughfare'].encode('utf-8')))
        except:
                row.append('')
        print row
        writer.writerow(row)

    else:
            print 'error'

此脚本在解析时成功,但未能将所有行放入我的csv中。它只做第一个。

0 个答案:

没有答案