GeospatialPython / pyshp

This library reads and writes ESRI Shapefiles in pure Python.
MIT License
1.1k stars 260 forks source link

Copy shape object from ShapeRecord #100

Closed abanduch closed 7 years ago

abanduch commented 7 years ago

`r = shapefile.Reader(r'...local\share\cartopy\shapefiles\natural_earth\cultural\10m_admin_1_states_provinces')

w = shapefile.Writer() w.fields = r.fields[1:] # skip first deletion field

for shaperec in r.iterShapeRecords():

if shapeRec.record[8] == 'California':

w.record(*shaperec.record)
w.shape(shaperec.shape)

w.save('shapefile/cal/test')`

when trying to use the above code from the docs, i get the following error:

`--------------------------------------------------------------------------- TypeError Traceback (most recent call last)

in () 7 #if shapeRec.record[8] == 'California': 8 w.record(*shaperec.record) ----> 9 w.shape(shaperec.shape) 10 11 w.save('shapefile/cal/test') C:\Program Files\Anaconda3\lib\site-packages\shapefile.py in shape(self, i) 1053 1054 def shape(self, i): -> 1055 return self._shapes[i] 1056 1057 def shapes(self): TypeError: list indices must be integers or slices, not _Shape `

My goal here is to copy only a portion of an existing shapefile to a new one.

karimbahgat commented 7 years ago

The problem here seems to be that you are using an older version of the library, but using the newest documentation. On GitHub, the master branch and README has been undergoing some radical changes, including renaming the _Shape class to Shape, and changing how the Writer.shape() method works, as in the documentation example you mentioned.

So if you update PyShp to the latest GitHub master branch, then your code should work. Alternatively, if you continue to use the older version, you can copy the shape object by changing w.shape(shaperec.shape) to w._shapes.append(shaperec.shape).

One thing that might have added to the confusion is that the changed master branch continued to use the same version number as the previous release (1.2.11). For clarity and in the future, I have now updated the major version number and added "-dev" to indicate that it's a non-stable development version.