Finding and adding to a .kml file using python

放肆的年华 提交于 2019-12-24 12:18:34

问题


I am not a very good coder. But I really want to automate something I have to do at work. Basically, I have a bunch of placemarkers in google earth showing hand-holes of a municipal fiber network. I have a few pictures of each hand-hole that I want to place as a tag in the .kml file. Basically, I want to have it so when they click on a placemarker in google earth, it brings up the little description bubble and shows the pictures for each hand-hole and probably some other vital info.

Right now I have each hand hole labeled as either TO-. So hand-hole number 101 has a TO-101. And I have already made a script that has renamed all the pictures to match the name. So, if hand hole TO-101 has 3 pictures, they would be TO-101-1.jpg, TO-101-2.jpg, TO-101-3.jpg.

So, basically, I am trying to make a python script that reads the kml file (which I have done succesfully). I need it to find the corresponding TO-101 or whichever handhole in the .kml file, add a line below that line that reads:

<description> <img src="TO-101-1.jpg"><img src="TO-101-2.jpg"></description>. 

Need to do this for about 5000 pictures and 2000 or so hand-holes.

I have tried to this:

import string, glob, sys, os, fileinput
f = open('./hand-holes.kml','r')

while f:
line = f.readline()
if line == "<name>TO-101</name>":
print line

And I can't even get it to find and print that line. I know the line is in the file, and I know the path is right. Because if I comment out the if line == "TO-101" it displays the contents of the file. So, if I can't even get that to work, there is no chance I am going to get the rest of it to work. I have tried looking at several pieces of search and replace type python example code. Some of it uses a string library, which I am not sure if I need to use.

Can anyone help me? Thanks

Renosis


回答1:


I'm assuming the reason your if line == "<name>TO-101</name>" line doesn't work is because it probably has whitespace preceding it. If you changed it to line.strip() == ... then it would presumably work.

Your best bet would be to implement an XML handler to read in the existing file, parse it, and add the new section. Start maybe with xml.sax



来源:https://stackoverflow.com/questions/6944708/finding-and-adding-to-a-kml-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!