使用python

时间:2016-07-20 12:09:14

标签: python csv geocoding

我有一个地址列表并使用GeoPy我获得了经度和纬度。一切都很好但现在我想将经度和纬度插入到相同的csv文件中,所以第8列的纬度和第9列的经度。

AREA, ADDRESS1, ADDRESS2, ADDRESS3, ADDRESS4, ADDRESS7, LATITUDE, LONGITUDE
NORRKÖPING, Fridtunga, 602 28, Norrköping,SE        
NORRKÖPING, Björnatan gata 131, 603 77, Norrköping,SE   

上面是我提取信息的csv文件。我正在接受地址2和4并获得它们的经度和纬度

from geopy.geocoders import Nominatim
import csv

geolocator = Nominatim()

with open('test.csv', 'r') as in_file:
reader = csv.reader(in_file)
for row in reader:
    adress1 = row[3]
    adress2 = row[5]
    locaiton = geolocator.geocode(adress1 + " " + adress2)
    if locaiton is not None and locaiton.longitude is not None and locaiton.latitude is not None:
        print(adress1 + " " + adress2 + " ", locaiton.latitude, locaiton.longitude)
        out_file = open('test.csv', 'w')
        writer = csv.writer(out_file)
        row[6] = locaiton.latitude
        row[7] = locaiton.longitude
        writer.writerow(row)

最后一部分是我无法弄清楚的部分。我怎样才能使它继续在行中继续?现在它将经度和纬度放在同一行,删除以前的行。

现在csv文件看起来像:

NORRKÖPING, Björnatan gata 131, 603 77, Norrköping,SE,58.5888632,16.186094499284, 

但我希望它看起来像:

 NORRKÖPING, Fridtunga, 602 28, Norrköping,SE, 58.5649201, 16.217851        
 NORRKÖPING, Björnatan gata 131, 603 77, Norrköping,SE,58.5888632,16.186094499284, 

1 个答案:

答案 0 :(得分:0)

添加内容时,不应该更改文件。 Check this question for that dicussion.但是,您可以使用所需的输出创建一个新文件。

假设您的代码有效,请尝试这样做,重新排列几行。

from geopy.geocoders import Nominatim
import csv

geolocator = Nominatim()

with open('test.csv','r') as in_file:
    reader = csv.reader(in_file)
    out_file = open('out.csv', 'w')
    writer = csv.writer(out_file)
    for row in reader:
        adress1 = row[3]
        adress2 = row[5]
        locaiton = geolocator.geocode(adress1 + " " + adress2)
        if locaiton is not None and locaiton.longitude is not None and locaiton.latitude is not None:
            print(adress1 + " " + adress2 + " ", locaiton.latitude, locaiton.longitude)
            row.append(locaiton.latitude) 
            row.append(locaiton.longitude)
            writer.writerow(row)