python csv在将浮点值写入列时写入错误

时间:2018-09-20 18:11:50

标签: python

我想将从url获取的值写到也有一些float值的csv文件中。下面的代码显示错误“找到浮动”。

import urllib2
import json
import csv

url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-10-01&endtime=2016-10-02'

i=0

csvfile = csv.writer(open('earthquakedet.csv', 'w'))
csvfile.writerow(["Latitude", "Longitude ","Title","Place","Mag"])

json_string = urllib2.urlopen(url).read()
j = json.loads(json_string)

names = [d['properties'] for d in j['features']]
names1 = [d['geometry'] for d in j['features']]

while i <= len(names):

    print names[i]['title']
    print names[i]['place']
    print names[i]['mag']
    print names1[i]['coordinates'][0]
    print names1[i]['coordinates'][1]
    i=i+1
   finalstr=float(names1[i]['coordinates'][0]) + float(names1[i]['coordinates'][1]) + names[i]['title'] + names[i]['place'] + names[i]['mag']

    csvfile.writerow(finalstr)


csvfile.close()

1 个答案:

答案 0 :(得分:0)

writerow接受要放在行中的值列表,而不是字符串。因此,与其将值自己串联起来,不如将它们放在列表中以传递给writerow

# ...
i = i + 1

csvfile.writerow([names1[i]['coordinates'][0], names1[i]['coordinates'][1], names[i]['title'], names[i]['place'], names[i]['mag']])