通过Python将CSV转换为KML

时间:2013-01-16 10:58:30

标签: python csv kml

我有一点问题我总是得到错误:

  

TypeError:无法连接'str'和'list'对象

import csv
import os
fp = "filepath/testfile.csv"
file = open(fp)
lines =file.readlines()
for line in lines:
    line = line.strip()
    fields = line.split(',') #comma seperated
    branch = fields[0].split() #splitting
    lat = fields[1].split()
    lng = fields[2].split()
    web = fields[3].split()
    email = fields[4].split()
    adress = fields[5].split()

    print ("branch: " + branch) #print splitted
    print ("lat: " + lat)
    print ("lng: " + lng)
    print ("web :" + web)
    print ("email: " + email)
    print ("address: " + address)

f = open('filepath/csv2kml.kml', 'w')
fname = "testing_Actions"
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
f.write("<Document>\n")
f.write("   <name>" + fname + '.kml' +"</name>\n")
for row in lines:
    f.write("   <Placemark>\n")
    f.write("       <ExtendedData>\n")
    f.write("           <Data name=the branch name>\n")
    f.write("               <value>\n")
    f.write("               " + str(branch) + "\n")
    f.write("               </value>\n")
    f.write("           </Data>\n")
    f.write("           </Data name=Web>\n")
    f.write("               <value>\n")
    f.write("               " + str(web) +"\n")
    f.write("               </value>\n")
    f.write("           </Data>\n")
    f.write("           </Data name=email>\n")
    f.write("               <value>\n")
    f.write("               " + str(email) + "\n")
    f.write("               </value>\n")
    f.write("           </Data>\n")
    f.write("       <description>" + str(address) + "</description>\n")
    f.write("       <Point>\n")
    f.write("           <coordinates>" + str(lat) + "," + str(lng) + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print ("File Created. ")
f.close
file.close()

我找不到我的错误。

3 个答案:

答案 0 :(得分:1)

我找不到我的错误

你可以。如果您完全阅读了错误消息,它还会告诉您错误发生在哪行中。

是在这里吗?

print ("branch: " + branch) #print splitted

并在以下行中尝试连接字符串"branch"和列表branch

尝试将其替换为:

print ("branch: {}".format(branch)) #print splitted

答案 1 :(得分:0)

更好的是,使用KML库:http://googlegeodevelopers.blogspot.ca/2012/01/introducing-pykml-python-library-for.html

几乎每种语言都有一种。

答案 2 :(得分:-3)

我解决了!

print ("branch: " + branch) #print splitted
print ("lat: " + lat)
print ("lng: " + lng)
print ("web :" + web)
print ("email: " + email)
print ("address: " + address)

编辑

print ("branch: " + `branch`) #print splitted
print ("lat: " + `lat`)
print ("lng: " + `lng`)
print ("web :" + `web`)
print ("email: " + `email`)
print ("address: " + `address`)

f.write("           <Data name=the branch name>\n")
f.write("               <value>\n")
f.write("               " + `branch` + "\n")
f.write("               </value>\n")
f.write("           </Data>\n")

等等