Python, Point Shapefile and Qgis: Part II

24 Oct

In my first post, I showed how to create a shapefile from an excel sheet – but it was hard coded by cell. Not very useful.  Here is the code to loop through the sheet and create shapefile, then send a text telling me the job finished. The last thing to do is render the shapefile – Mapnik would work for this.
Here is the code:

import shapefile
import xlrd
import smtplib
book = xlrd.open_workbook(“NAME OF XLS FILE.XLS”)
sh = book.sheet_by_index(0)
w = shapefile.Writer(shapefile.POINT)

def readRow():

for rownum in range(sh.nrows):
w.point(sh.cell_value(rowx=rownum, colx=0), sh.cell_value(rowx=rownum, colx=1))
w.record(sh.cell_value(rowx=rownum, colx=2),sh.cell_value(rowx=rownum, colx=3))
print ‘Reading Record: ‘+ str(rownum)

print ‘Complete…’

message = ‘Job Complete’
server = smtplib.SMTP( ‘’, 587 )
server.login( ‘’, YOUR PASSWD’ )
server.sendmail( ‘YOUR PHONE’, ‘TO PHONE’, message )

The code opens the excel file formatted as: Lat, Long, Type, Address. Creates a point shapfile with fields for type and address.  Create a function that loops through the excel sheet. The Long, Lat, Type and Address are always in the same column so we only need to replace the row number of our cell and we do that by using the rownum variable in the loop.

While running, it will print out the current rownumber then print Complete.. when done. Lastly, It will send a text message saying that it has finished.

Simple.  Less than 25 lines of code. Set this to run as a task in Windows or as a Cron Job.


3 Responses to “Python, Point Shapefile and Qgis: Part II”

  1. Sam007 November 15, 2012 at 8:34 pm #

    I was recently struggling on creating the same .prj file for my shapefiles from CSV using I hit upon this code, and I was able to create the .prj file. Since I had 90k+ CSV files, opening QGIS for everyone was not a feasible option.

    • paulcrickard November 15, 2012 at 8:37 pm #

      Glad you found it. Looks like the guy who developed runs a blog called goespatial python. Awesome code on his blog.


  1. Python, Point Shapefile and Qgis « Architecture and Planning - October 24, 2012

    […] ← Crime Mapping: Kernel Density Estimation Python, Point Shapefile and Qgis: Part II → […]

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: