pythonkml

Trying to make a KML file in Python


I'm still very new to python, i am trying to export the locations on a list (List2) into a kml file which will then display the results on google maps. I have no idea really what i am doing and atm all i am getting is a syntax error around every ,", symbol. Can someone help me with this please.

KMLFile = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
    f.write("   <Placemark>")
    f.write("       <decription>" + str(row[0]) + "</description>")
    f.write("       <Point>")
    f.write("          <coordinates>" + str(row[2]) + str(row[1])"</coordinates>")
    f.write("       </Point>")
    f.write("   </Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
KMLFile = close()

Solution

  • In brief:

    Your corrected code:

    f = open("KML.txt", "w")
    f.write("<KML_File>\n")
    f.write("<Document>\n")
    for line in List2:
        f.write("\t<Placemark>")
        f.write("\t\t<decription>" + str(row[0]) + "</description>")
        f.write("\t\t<Point>")
        f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
        f.write("\t\t</Point>")
        f.write("\t</Placemark>")
    f.write("</Document>\n")
    f.write("</kml>\n")
    f.close()
    

    In addition, if you do not want to write the f.close() line and let python manage the file closure:

    with open("KML.txt", "w") as f:
        f.write("<KML_File>\n")
        f.write("<Document>\n")
        for line in List2:
            f.write("\t<Placemark>")
            f.write("\t\t<decription>" + str(row[0]) + "</description>")
            f.write("\t\t<Point>")
            f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
            f.write("\t\t</Point>")
            f.write("\t</Placemark>")
        f.write("</Document>\n")
        f.write("</kml>\n")
    

    Eventually, if you do not want to have many + into your f.write() lines, you can also opt for the format() method:

    f.write("\t\t\t<coordinates>{}{}/coordinates>".format(row[2], row[1]))