我有一个小程序,它从数据库Yay返回某些用户位置的结果。我想将这些结果分别放在CSV中各自的列中。你将如何构建,以便csv读取IP,国家,城市......
import pygeoip
import csv
def ipLocator(ip):
with open('ips.csv', 'wb') as csvfile:
writer = csv.writer(csvfile)
GeoIPDatabase = 'GeoLiteCity.dat'
ipData = pygeoip.GeoIP(GeoIPDatabase)
record = ipData.record_by_name(ip)
try:
print("%s" % ip)
print("%s, %s, %s" % (record['city'], record['region_code'], record['country_name']))
print("%s" % (record['metro_code']))
except:
print("Failed %s" % ip)
def ip():
with open('ipaddresses.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
print readCSV
for row in readCSV:
print ipLocator(row[0])
with open('test.csv', 'wb') as fp:
a = csv.writer(fp, delimiter=',')
data = [['city'],['region_code'],['country_name']]
a.writerows(data)
ip()
更新
import pygeoip
import csv
import os
def ipLocator(ip):
GeoIPDatabase = 'GeoLiteCity.dat'
ipData = pygeoip.GeoIP(GeoIPDatabase)
record = ipData.record_by_name(ip)
try:
print("%s" % ip)
print("%s, %s, %s" % (record['city'], record['region_code'], record['country_name']))
print("%s" % (record['metro_code']))
except:
print("Failed %s" % ip)
def ip():
with open('ipaddresses.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
print readCSV
for row in readCSV:
print ipLocator(row[0])
with open('output.csv', 'wb') as outfile:
csv_writer = csv.writer(outfile, delimiter=',')
csv_writer.writerows(row[0])
ip()
这将返回垂直打印的批次的最后一个ipaddress,占据csv第一列的第一列:
这不是我追求的目标