摘要: 在平时的数据处理中,经常会遇到将字符串或JSON格式数据转成空间数据的需求,使用ArcGIS Engine 或者shapelib单独写个应用程序比较麻烦,需要开发环境。编译,调试等等。那么使用python 直接操作shapefile 是一个比较好的选择。 py...
在平时的数据处理中,经常会遇到将字符串或JSON格式数据转成空间数据的需求,使用ArcGIS Engine 或者shapelib单独写个应用程序比较麻烦,需要开发环境。编译,调试等等。那么使用python 直接操作shapefile 是一个比较好的选择。
pyshp 下载地址:
https://code.google.com/p/pyshp/
pyshp的使用比较简单
1.下载pyshp,将其放到python的根目录下(当然也可以通过设置path等方式来引用)
2.import shapefile
3.对shapefile进行操作
Reading Points in Shapes >>> import shapefile >>> sf = shapefile.Reader("shapefiles/blockgroups") >>> shapes = sf.shapes() >>> # Read the bounding box from the 4th shape >>> shapes[3].bbox [-122.485792, 37.786931000000003, -122.446285, 37.811019000000002] >>># Read the 8th point in the 4th shape >>> shapes[3].points[7] [-122.471063, 37.787402999999998] Reading Database Attributes >>> # Read the field descriptors for the database file >>> sf.fields [("DeletionFlag", "C", 1, 0), ["AREA", "N", 18, 5], ... ["BKG_KEY", "C", 12, 0], ["POP1990", "N", 9, 0], ["POP90_SQMI", "N", 10, 1], ... ["HOUSEHOLDS", "N", 9, 0], ... ["MALES", "N", 9, 0], ["FEMALES", "N", 9, 0]] >>> # Read the 2nd and 3rd field values of the 4th database record >>> sf.records[3][1:3] ['060750601001', 4715] Writing Shapefiles >>> import shapefile >>> # Make a point shapefile >>> w = shapefile.Writer(shapefile.POINT) >>> w.point(90.3, 30) >>> w.point(92, 40) >>> w.point(-122.4, 30) >>> w.point(-90, 35.1) >>> w.field('FIRST_FLD') >>> w.field('SECOND_FLD','C','40') >>> w.record('First','Point') >>> w.record('Second','Point') >>> w.record('Third','Point') >>> w.record('Fourth','Point') >>> w.save('shapefiles/test/point') >>> # Create a polygon 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')