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
w.field('FLD2','C','20')
w.field('FLD3','C','20')
w.field('FLD4','C','20')
w.field('FLD5','N','20')
w.field('FLD6','N','20')
w.field('FLD7','C','20')
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:
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.TypeError: iteration over non-sequence for the
w.poly(sr.shape)
Answer
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:
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
w.records.extend(r.records())
# Copy over the existing polygons
w._shapes.extend(r.shapes())
# Add a new polygon
w.poly(parts=[[[-104,24],[-104,25],[-103,25],[-103,24],[-104,24]]])
# Add a new dbf record for our polygon making sure we include
# all of the fields in the original file (r.fields)
w.record("STANLEY","TD","091022/1500","27","21","48","ep")
# Overwrite the old shapefile or change the name and make a copy
w.save(file_name)
No comments:
Post a Comment