Удалить запись из шейп-файла с помощью Python
У меня есть шейп-файл ESRI .shp
(со всеми связанными файлами, такими как .shx
, .dbf
и многое другое), которое я хочу отредактировать - мне нужно удалить первую запись и сохранить файл.
Для этого я установил pyshp
и попытался разобрать и отредактировать шейп-файл. Вот что я попробовал:
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()
Однако запись все еще доступна во вновь сохраненном файле.
К сожалению, документация не углубляется в эти вещи.
Как я могу достичь своей цели? Как проверить, что удаление прошло успешно перед сохранением файла?
2 ответа
Я не знаком с 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
Следуя именно той процедуре, которую вы описали, мне кажется, она отлично работает. Я начинаю с открытия шейп-файла:
>>> 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 = shapefile.Editor('example')
И я вижу, что теперь он имеет только две формы:
>>> e.shapes()
[<shapefile._Shape instance at 0x7f6cb5f6e518>, <shapefile._Shape instance at 0x7f6cb5f6e560>]