在 Python 中从 csv 创建 kml [英] Create kml from csv in Python

查看:41
本文介绍了在 Python 中从 csv 创建 kml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.我正在处理 gps 文件.我需要将包含所有 gps 数据的 CSV 文件转换为 kml 文件.下面是我正在使用的python中的代码:

I am new to Python. I am working on gps files. I need to convert a CSV file having all the gps data to kml file. Below is the code in python I am using :

import csv
#Input the file name.
fname = raw_input("Enter file name WITHOUT extension: ")
data = csv.reader(open(fname + '.csv'), delimiter = ',')
#Skip the 1st header row.
data.next()
#Open the file to be written.
f = open('csv2kml.kml', 'w')

#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>
")
f.write("<kml xmlns='http://earth.google.com/kml/2.1'>
")
f.write("<Document>
")
f.write("   <name>" + fname + '.kml' +"</name>
")
for row in data:
    f.write("   <Placemark>
")
    f.write("       <name>" + str(row[1]) + "</name>
")
    f.write("       <description>" + str(row[0]) + "</description>
")
    f.write("       <Point>
")
    f.write("           <coordinates>" + str(row[3]) + "," + str(row[2]) + "," + str(row[4]) + "</coordinates>
")
    f.write("       </Point>
")
    f.write("   </Placemark>
")
f.write("</Document>
")
f.write("</kml>
")
print "File Created. "
print "Press ENTER to exit. "
raw_input()

我使用的 csv 文件可在此处获得:dip12Sep11newEdited.csv生成的 kml 文件可在此处获得:csv2kml.kml但是没有正确创建 kml 文件.显然,在 csv 中的某些行之后,代码无法生成更多地标.它无法迭代.您可以通过滚动到生成的 kml 文件的最后部分来查看.

The csv file I am using is available here : dip12Sep11newEdited.csv The kml file generated is available here : csv2kml.kml But the kml file is not getting created correctly. Apparently after some rows in the csv the code is not able to generate more Placemarks. Its not able to iterate. You can see that by scrolling to the last part of the kml file generated.

谁能帮我找出代码中的错误,因为对于一些较小的 csv 文件,它可以正常工作并完全创建 kml 文件.

Can anyone help me finding out the error in the code, because for some smaller csv files it worked correctly and created kml files fully.

谢谢.

推荐答案

你没有回答上面的问题,但我猜错误是你没有关闭你的输出文件(这会刷新你的输出).

You didn't answer the query above, but my guess is that the error is that you're not closing your output file (which would flush your output).

f.close()

这篇关于在 Python 中从 csv 创建 kml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆