WARNING: I have no formal training in computer programming. I do not claim that this is elegant programming, and I am probably violating all kinds of naming and structural conventions. But the program works, and I feel like a superhero.
The Objective (see my last post): Write a program (script) that takes a 3-column txt-file as input (borehole number, latitude, longitude) and converts this into a KML file that I can open in and plot with Google Earth.
Trouble: The hardest part was figuring out that unless my txt file is in UTF-8, the numbers were getting al screwed up. Somehow, I ended up with extra whitespace between the digits of my coordinates. Other than that, all this was very straightforward with a good Python reference at hand. Like I said, this was my first program !
Here is the code:
print “\nProgram will convert a 3-column TXT-file (UTF-8) \n
Borehole No. – Latitude – Longitude \n
into a KML file that can be plotted in Google Earth.”
newfile=[]
file_name = raw_input(“Enter file name: “) # Open a source TXT file with coordinate data
text_file = open(file_name, “r”)
lines = text_file.readlines()
for line in lines: # Read coordinates into a list, line by line
alist=line.split() # alist[0]=Borehole,alist[1]=Latitude,alist[2]=Longitude
print ”’Borehole %s is located at latitude %s and longitude %s”’ % (alist[0],alist[1],alist[2])
newfile.append(alist) # Collect the lists with coordinate data in another list
text_file.close()
file_name = raw_input(“Enter file name for KML output: “) # Select name for Output file
text_file = open(file_name, ‘w’) # Create file to save KML text in
kmlheader=”’<?xml version=”1.0″ encoding=”UTF-8″?><kml xmlns=”http://www.opengis.net/kml/2.2“>
<Folder><name>%s</name>”’ % (file_name)
text_file.writelines(kmlheader) # Write tags to file
for borehole in newfile:
kmltext=”’<Placemark><name>%s</name><Point><coordinates>%s,%s,0</coordinates></Point></Placemark>”’ % (borehole[0],borehole[1],borehole[2]) # Create coordinate data
text_file.writelines(kmltext) # Write coordinate data to file
kmlfooter=”’</Folder></kml>”’ # Create kml closing tags
text_file.writelines(kmlfooter) # Add kml closing tags
text_file.close()
1 response so far ↓
Personal Technology Quest « Blogs will be Blogs… // June 3, 2009 at 4:33 pm |
[...] Personal Technology Quest I have finally returned to my computer programming adventures from last year. I just completed my first programming project. It’s short and sweet and actually helps me with what I’m doing at work. You can read about it here. [...]