gis.py 1.7 KB

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