My First Program in Python

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:

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()

# Read coordinates into a list, line by line
# alist[0]=Borehole,alist[1]=Latitude,alist[2]=Longitude
# Collect the lists with coordinate data in another list => newfile

for line in lines:
    print ”’Borehole %s is located at latitude %s and longitude %s”’ % (alist[0],alist[1],alist[2])

# Select name for Output file
file_name = raw_input(“Enter file name for KML output: “)  

# Create file to save KML text in
text_file = open(file_name, ‘w’)    
kmlheader=”'<?xml version=”1.0″ encoding=”UTF-8″?>\
<kml xmlns=”″&gt; \
<Folder><name>%s</name>”’ % (file_name)

text_file.writelines(kmlheader)  # Write tags to file          
for borehole in newfile:  # Create coordinate data
    kmltext=”'<Placemark><name>%s</name><Point><coordinates>%s,%s,0</coordinates></Point></Placemark>”’ % (borehole[0],borehole[1],borehole[2])   
    text_file.writelines(kmltext) # Write coordinate data to file
    kmlfooter=”'</Folder></kml>”’ # Create kml closing tags
text_file.writelines(kmlfooter)  # Add kml closing tags




Filed under Uncategorized

2 responses to “My First Program in Python

  1. Pingback: Personal Technology Quest « Blogs will be Blogs…

  2. Pingback: GIS on a Shoestring « Adventures in GIS

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s