GeospatialPython / pyshp

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

Fix exception thrown when writing empty records #194

Closed Jonty closed 4 years ago

Jonty commented 4 years ago

e.g.

Traceback (most recent call last):
File "filter_shp.py", line 12, in <module>
    w.record(*shaperec.record)
File "shapefile.py", line 1663, in record
    self.__dbfRecord(record)
File "shapefile.py", line 1675, in __dbfRecord
    if not self.fields[0][0].startswith("Deletion"):
IndexError: list index out of range
Exception ignored in: <function Writer.__del__ at 0x107810730>
Traceback (most recent call last):
File "shapefile.py", line 1157, in __del__
File "shapefile.py", line 1176, in close
shapefile.ShapefileException: When saving both the dbf and shp file, the number of records (1) must correspond with the number of shapes (0)
karimbahgat commented 4 years ago

Thanks for pointing out this uninformative error when the shapefile writer has no fields defined. However, according to ESRI, "the dBASE file must contain at least one field.", so we can't just skip the error. Instead, I just added a more informative exception when attempting to close a writer with no fields, to avoid writing invalid shapefiles, but adding you to the list of contributors. To truly write empty files, you will have to define at least one dummy field.

Jonty commented 4 years ago

This is great, thanks!