gis.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. '''
  2. @author: olivier.massot, sept. 2018
  3. '''
  4. import shapefile
  5. POINT = 1
  6. POLYLINE = 3
  7. POLYGON = 5
  8. SHAPE_NAMES = {1: "POINT", 3:"POLYLIGNE", 5:"POLYGONE"}
  9. class ShapeError(IOError): pass
  10. class SridError(IOError): pass
  11. class ShapeFile():
  12. def __init__(self, path_, srid=None):
  13. self.path_ = path_
  14. self.srid = srid
  15. def __enter__(self):
  16. if not self.path_.isfile():
  17. raise FileNotFoundError("Fichier introuvable")
  18. try:
  19. self.sf = shapefile.Reader(self.path_)
  20. except shapefile.ShapefileException:
  21. raise ShapeError("Fichier Shape illisible")
  22. if not self.sf.shapeType in (POINT, POLYLINE, POLYGON):
  23. raise ShapeError("Type de géométrie non reconnue")
  24. # if self.srid is not None:
  25. # if not self.sf.srid == self.srid:
  26. # raise SridError("Le SRID du fichier doit être '{}'".format(self.srid))
  27. return self
  28. def shape(self):
  29. return self.sf.shapeType
  30. def fields(self):
  31. return [f[0] for f in self.sf.fields if f[0] != 'DeletionFlag']
  32. def records(self):
  33. for record in self.sf.shapeRecords():
  34. yield record
  35. def __exit__(self, exc_type, exc_val, exc_tb):
  36. del self.sf