I am looking to do a simple append using Pyshp and keep running into walls. The editor object could not read the dbf header for the input shapefile so I tried using reader and writer as suggested but have run into some problems with writer.

Initially I wanted to copy entire ShapeRecord objects but did not see a way to use writer to write them, so I tried a more granular approach like iterating and copying shape and record attributes which failed as well:

reader = shapefile.Reader('c:/temp/input.shp') #Open input file
w = shapefile.Writer(shapefile.POLYGON)        #Create writer
w.field('FLD1','C','20')                       #Create fields
for sr in reader.shapeRecords():         #iterate through shapeRecords in the input
    w.poly(sr.shape)                     #write shape to writer
    w.record(sr.record)                  #write record to writer
w.save('c:/temp/appendoutput.shp')       #save writer to file

I end up with two errors:

  1. IndexError: tuple index out of range for w.record(sr.record) File "C:\Python26\ArcGIS10.0\lib\shapefile.py", line 959, in record [record.append(recordList[i]) for i in range(fieldCount)]
    This perplexes me since print sr.record shows me that there are seven items in the record list that was read in by the reader and I have seven fields.

  2. TypeError: iteration over non-sequence for the w.poly(sr.shape)

  • I don't see any way to PM on this forum or an email link. I am currently working with NHC data here: nhc.noaa.gov/gis/forecast/archive. If you download one of the <storm designation>_5day_*.zip files it will have a point, line, and polygon layer in it. I am working on the polygon one at present. Thanks!!!! – user2803687 Sep 26 '13 at 17:28

Make sure you are using the latest pyshp (version 1.2). I used the following noaa nhc shapefile in the example: "ep202009.026_5day_pgn"

I was able to add another polygon. In this image the original is the circle and mine is the square:

shapefile example

Here is the code with lots of comments:

import shapefile
# Polygon shapefile we are updating.
# We must include a file extension in
# this case because the file name
# has multiple dots and pyshp would get
# confused otherwise.
file_name = "ep202009.026_5day_pgn.shp"
# Create a shapefile reader
r = shapefile.Reader(file_name)
# Create a shapefile writer
# using the same shape type
# as our reader
w = shapefile.Writer(r.shapeType)
# Copy over the existing dbf fields
w.fields = list(r.fields)
# Copy over the existing dbf records
# Copy over the existing polygons
# Add a new polygon
# Add a new dbf record for our polygon making sure we include
# all of the fields in the original file (r.fields)
# Overwrite the old shapefile or change the name and make a copy 
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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