在Python中从csv创建kml

发布于 2024-12-06 04:40:50 字数 1676 浏览 0 评论 0原文

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

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'?>\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 data:
    f.write("   <Placemark>\n")
    f.write("       <name>" + str(row[1]) + "</name>\n")
    f.write("       <description>" + str(row[0]) + "</description>\n")
    f.write("       <Point>\n")
    f.write("           <coordinates>" + str(row[3]) + "," + str(row[2]) + "," + str(row[4]) + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print "File Created. "
print "Press ENTER to exit. "
raw_input()

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

任何人都可以帮助我找出代码中的错误,因为对于一些较小的 csv 文件,它可以正常工作并完全创建 kml 文件。

谢谢。

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'?>\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 data:
    f.write("   <Placemark>\n")
    f.write("       <name>" + str(row[1]) + "</name>\n")
    f.write("       <description>" + str(row[0]) + "</description>\n")
    f.write("       <Point>\n")
    f.write("           <coordinates>" + str(row[3]) + "," + str(row[2]) + "," + str(row[4]) + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print "File Created. "
print "Press ENTER to exit. "
raw_input()

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.

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.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

楠木可依 2024-12-13 04:40:51

使用 etree 创建文件

http://docs.python.org/library/xml .etree.elementtree.html

它包含在 Python 中,可以防止您生成损坏的 XML。 (例如,因为 fname 包含 &,它在 XML 中具有特殊含义。)

use etree to create your file

http://docs.python.org/library/xml.etree.elementtree.html

It's included with Python and protects you from generating broken XML. (eg. because fname contained &, which has special meaning in XML.)

马蹄踏│碎落叶 2024-12-13 04:40:51

这段代码写得很好,谢谢您的帖子。我通过将 CSV 放在与 .py 代码相同的目录中来使其工作。

我做了一些编辑,将其带到 py 3.3

import csv
#Input the file name."JoeDupes3_forearth"
fname = 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'?>\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 data:
    f.write("   <Placemark>\n")
    f.write("       <name>" + str(row[1]) + "</name>\n")
    f.write("       <description>" + str(row[3]) + "</description>\n")
    f.write("       <Point>\n")
    f.write("           <coordinates>" + str(row[10]) + "," + str(row[11]) + "," + str() + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print ("File Created. ")
print ("Press ENTER to exit. ")
input()
f.close()

希望它可以帮助您尝试转换数据。

This code is well written thank you for the post. I got it to work by putting my CSV in the same directory as the .py code.

I made a few edits to bring it to py 3.3

import csv
#Input the file name."JoeDupes3_forearth"
fname = 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'?>\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 data:
    f.write("   <Placemark>\n")
    f.write("       <name>" + str(row[1]) + "</name>\n")
    f.write("       <description>" + str(row[3]) + "</description>\n")
    f.write("       <Point>\n")
    f.write("           <coordinates>" + str(row[10]) + "," + str(row[11]) + "," + str() + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print ("File Created. ")
print ("Press ENTER to exit. ")
input()
f.close()

Hope it helps if you are trying to convert your data.

笑看君怀她人 2024-12-13 04:40:51

一个答案提到了 "etree",这是您不知道的一个优点必须对 xml 格式进行硬编码:

下面是我的一个示例,当然您必须根据您的情况进行调整,但是您可能会了解 etree 工作原理的原理:

要获得类似的内容,

<OGRVRTDataSource>
 <OGRVRTLayer name="GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H">
  <SrcDataSource>G:\AMSR\GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H.csv</SrcDataSource>
  <GeometryType>wkbPoint</GeometryType>
  <GeometryField encoding="PointFromColumns" x="lon" y="lat" z="brightness" />
 </OGRVRTLayer>
</OGRVRTDataSource>

您可以使用以下代码:

import xml.etree.cElementTree as ET
[....]
root = ET.Element("OGRVRTDataSource")

OGRVRTLayer  = ET.SubElement(root, "OGRVRTLayer")
OGRVRTLayer.set("name", AMSRcsv_shortname)

SrcDataSource = ET.SubElement(OGRVRTLayer, "SrcDataSource")
SrcDataSource.text = AMSRcsv

GeometryType = ET.SubElement(OGRVRTLayer, "GeometryType")
GeometryType.text = "wkbPoint"

GeometryField = ET.SubElement(OGRVRTLayer,"GeometryField")
GeometryField.set("encoding", "PointFromColumns")

GeometryField.set("x", "lon")
GeometryField.set("y", "lat")
GeometryField.set("z", "brightness")

tree = ET.ElementTree(root)
tree.write(AMSRcsv_vrt)

还有更多信息此处

One answer mentions the "etree", one advantage that you do not have to hardcode the xml format:

Below one of my examples, of course you have to adjust it to your case, but you may get the principle idea of how etree works:

to get something like this

<OGRVRTDataSource>
 <OGRVRTLayer name="GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H">
  <SrcDataSource>G:\AMSR\GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H.csv</SrcDataSource>
  <GeometryType>wkbPoint</GeometryType>
  <GeometryField encoding="PointFromColumns" x="lon" y="lat" z="brightness" />
 </OGRVRTLayer>
</OGRVRTDataSource>

you can use this code:

import xml.etree.cElementTree as ET
[....]
root = ET.Element("OGRVRTDataSource")

OGRVRTLayer  = ET.SubElement(root, "OGRVRTLayer")
OGRVRTLayer.set("name", AMSRcsv_shortname)

SrcDataSource = ET.SubElement(OGRVRTLayer, "SrcDataSource")
SrcDataSource.text = AMSRcsv

GeometryType = ET.SubElement(OGRVRTLayer, "GeometryType")
GeometryType.text = "wkbPoint"

GeometryField = ET.SubElement(OGRVRTLayer,"GeometryField")
GeometryField.set("encoding", "PointFromColumns")

GeometryField.set("x", "lon")
GeometryField.set("y", "lat")
GeometryField.set("z", "brightness")

tree = ET.ElementTree(root)
tree.write(AMSRcsv_vrt)

also some more info here

忘东忘西忘不掉你 2024-12-13 04:40:51

simplekml 软件包工作得很好,可以轻松完成这些事情。

要在 Ubuntu 上安装,请下载最新版本并从包含存档内容的目录运行以下命令。

sudo python setup.py install

还有一些教程帮助您入门。

The simplekml package works very well, and makes easy work of such things.

To install on Ubuntu, download the latest version and run the following from the directory containing the archive contents.

sudo python setup.py install

There are also some tutorials to get you started.

心奴独伤 2024-12-13 04:40:51

只需使用 simplekml 库即可轻松创建 kml.. 而不是编写 kml 数据.. 我直接使用 simplekml 实现了它。

import simplekml

阅读 simplekml 的文档

with open(arguments+'.csv', 'r') as f:
    datam = [(str(line['GPSPosLongitude']), str(line['GPSPosLatitude'])) for line in csv.DictReader(f)]
    kml = simplekml.Kml()
    linestring = kml.newlinestring(name='linename')
    linestring.coords = datam
    linestring.altitudemode = simplekml.AltitudeMode.relativetoground
    linestring.style.linestyle.color = simplekml.Color.lime
    linestring.style.linestyle.width = 2
    linestring.extrude = 1
    kml.save('file.kml')
    kml.savekmz('file.kmz', format=False)
    kml2geojson.main.convert('file.kml', '')

Just use simplekml library to create kml easily.. instead of writing the kml data.. I achieved it directly by using simplekml.

import simplekml

Read the documentation of simplekml

with open(arguments+'.csv', 'r') as f:
    datam = [(str(line['GPSPosLongitude']), str(line['GPSPosLatitude'])) for line in csv.DictReader(f)]
    kml = simplekml.Kml()
    linestring = kml.newlinestring(name='linename')
    linestring.coords = datam
    linestring.altitudemode = simplekml.AltitudeMode.relativetoground
    linestring.style.linestyle.color = simplekml.Color.lime
    linestring.style.linestyle.width = 2
    linestring.extrude = 1
    kml.save('file.kml')
    kml.savekmz('file.kmz', format=False)
    kml2geojson.main.convert('file.kml', '')
︶葆Ⅱㄣ 2024-12-13 04:40:50

您没有回答上面的查询,但我的猜测是错误是您没有关闭输出文件(这会刷新您的输出)。

f.close()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文