6

I would like to generate a .shp with five points using shapefile available through pyshp. However, when I loop through my list I get only the last value. This makes sense as I did not append any of the points to an empty list (e.g. new_shp = [])

import shapefile as sf
import os

filename2 = 'test/point10'
lis = [(33.21, -122.15, 'france'), (35.31, -122.15, 'germany'), (35.41, -123.15, 'Hawaii'), (30.51, -122.15, 'Philippines'),(32.30, -122.15, 'Texas')]
for l in lis:
    w = sf.Writer(sf.POINT)
    w.point(l[0], l[1])
    w.field('location')
    w.record(l[2], 'Point')
    w.save(filename2)

# create the PRJ file
prj = open("%s.prj" % filename2, "w")
epsg = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]'
prj.write(epsg)
prj.close()

I am assumming that I have to append all the points somewhere in the for loop, but I don't understand how to actually append it. How do I effectively loop through lis to get a .shp file with all five points?

1 Answer 1

5

It looks like you're creating a single point and constantly overwriting the shapefile with just that single point file. Try moving your instance of the sf.Writer class before your for loop and saving filename2 after the for loop.

w = sf.Writer(sf.POINT)
for l in lis:
    w.point(l[0], l[1])
    w.field('location')
    w.record(l[2], 'Point')
w.save(filename2)
2
  • Thanks @Mintx. I figured I had to do that and had an error a couple of times...then I noticed that had to move one more thing out of the loop, the 'w.field('location')' also had to go before the loop. Thanks again!
    – hylaeus
    Commented Nov 15, 2012 at 21:52
  • I mean w.field('location'), had to go outside of the loop too.
    – hylaeus
    Commented Nov 15, 2012 at 22:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.