2

This is the test code I have written:

import shapefile
w = shapefile.Writer(shapefile.POLYGON)
w.poly(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])
w.field('FIRST_FLD','C','40')
w.field('SECOND_FLD','C','40')
w.record('First','Polygon')
w.save('shapefiles/test/polygon')

However, it does not work and I am prompted with an error:

Traceback (most recent call last):   
  File "C:\src\Python\coordinates.py", line 33, in <module>
    w = shapefile.Writer(shapefile.POINT) #shapefile.POLYGON)
  File "C:\Python39\lib\site-packages\shapefile.py", line 1293, in __init__
    self.shp = self.__getFileObj(os.path.splitext(target)[0] + '.shp')
  File "C:\Python39\lib\ntpath.py", line 204, in splitext
    p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not int

What seems to be the problem?

1

Where did you get that code from? It appears to relate to an older version of the shapefile module. Always check the documentation corresponding to your version. The latest docs are here:

https://github.com/GeospatialPython/pyshp#writing-shapefiles

and show that you create a Writer the the target file name and then close it to save the shapefile. This is the current way of what you are doing:

>>> w = shapefile.Writer('shapefiles/test/testfile')
>>> w.poly([[[1,5],[5,5],[5,1],[3,3],[1,1]]])
>>> w.field('FIRST_FLD','C','40')
>>> w.field('SECOND_FLD','C','40')
>>> w.record('First','Polygon')
>>> w.close()

Which produces a shapefile like this:

INFO: Open of `shapefiles/test/testfile.shp'
      using driver `ESRI Shapefile' successful.

Layer name: testfile
Metadata:
  DBF_DATE_LAST_UPDATE=2020-12-14
Geometry: Polygon
Feature Count: 1
Extent: (1.000000, 1.000000) - (5.000000, 5.000000)
Layer SRS WKT:
(unknown)
FIRST_FLD: String (40.0)
SECOND_FLD: String (40.0)
OGRFeature(testfile):0
  FIRST_FLD (String) = First
  SECOND_FLD (String) = Polygon
  POLYGON ((1 5,5 5,5 1,3 3,1 1,1 5))
4

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.