代码之家  ›  专栏  ›  技术社区  ›  cezar Dennis Kioko

使用python从shapefile中删除记录

  •  0
  • cezar Dennis Kioko  · 技术社区  · 7 年前

    我有一个ESRI形状文件 .shp (所有相关文件,如 .shx , .dbf 还有更多)我要编辑的内容-我需要删除第一条记录并保存文件。

    为此,我安装了 pyshp 并尝试分析和编辑shapefile。这就是我所尝试的:

    import shapefile
    e = shapefile.Editor('location/of/my/shp')
    e.shapes()
    # example output
    >>> [<shapefile._Shape instance at 0x7fc5e18d93f8>,
         <shapefile._Shape instance at 0x7fc5e18d9440>,
         <shapefile._Shape instance at 0x7fc5e18d9488>,
         <shapefile._Shape instance at 0x7fc5e18d94d0>,
         <shapefile._Shape instance at 0x7fc5e18d9518>]
    

    我想从这里删除第一个条目 <shapefile._Shape instance at 0x7fc5e18d93f8> 然后保存文件:

    e.delete(0) # I tried e.delete(shape=0) too
    e.save()
    

    但是,该记录在新保存的文件中仍然可用。

    不幸的是 documentation 没有深入了解这些事情。

    我怎样才能实现我的目标?如何在保存文件之前检查删除是否成功?

    2 回复  |  直到 7 年前
        1
  •  2
  •   larsks    7 年前

    完全按照你描述的程序对我来说似乎很好。我首先打开一个形状文件:

    >>> e = shapefile.Editor('example')
    

    此文件有三种形状:

    >>> e.shapes()
    [<shapefile._Shape instance at 0x7f6cb5f67dd0>, <shapefile._Shape instance at 0x7f6cb5f67f38>, <shapefile._Shape instance at 0x7f6cb5f6e050>]
    

    我删除第一个形状并保存文件:

    >>> e.delete(0)
    >>> e.save('example')
    

    现在我重新打开文件:

    >>>e=形状文件。编辑器(“示例”)
    

    我可以看到它现在只有两种形状:

    >>> e.shapes()
    [<shapefile._Shape instance at 0x7f6cb5f6e518>, <shapefile._Shape instance at 0x7f6cb5f6e560>]
    
        2
  •  1
  •   Marcelo Villa-Piñeros    7 年前

    我不熟悉 pyshp 但这可以通过使用 ogr ,它允许使用矢量数据,并使 gdal 图书馆

    from osgeo import ogr
    
    fn = r"file.shp"  # The path of your shapefile
    ds = ogr.Open(fn, True)  # True allows to edit the shapefile
    lyr = ds.GetLayer()
    
    print("Features before: {}".format(lyr.GetFeatureCount()))
    lyr.DeleteFeature(0)  # Deletes the first feature in the Layer
    
    # Repack and recompute extent
    # This is not mandatory but it organizes the FID's (so they start at 0 again and not 1)
    # and recalculates the spatial extent.
    ds.ExecuteSQL('REPACK ' + lyr.GetName())
    ds.ExecuteSQL('RECOMPUTE EXTENT ON ' + lyr.GetName())
    
    print("Features after: {}".format(lyr.GetFeatureCount()))
    
    del ds