使用Python将自定义功能属性添加到ESRI Shapefile

mat*_*ard 6 esri shapefile osgeo geodjango ogr

我正在寻找一种方法来获取一个功能集为200个国家的现有ESRI Shapefile.每个国家/地区要素都具有"NAME"属性.我的目标是创建一个Python脚本,添加一个任意(现在)的附加属性,比如"POPULATION".

当然我安装了OSGeo和GeoDjango模块.我到目前为止:

from osgeo import ogr

infile = ogr.Open('sample.shp', 1) #'sample.shp' is a pre-existing ESRI shapefile described above
inlyr = infile.GetLayerByIndex(0)
Run Code Online (Sandbox Code Playgroud)

我错过了一个OGR函数,它允许我将Feature属性字段插入现有的Shapefile中吗?

Sam*_*uel 7

要添加字段,您必须创建一个OGRFieldDefn,然后调用inlyr.CreateField

fieldDefn = ogr.FieldDefn('POPULATION', ogr.OFTReal) 
fieldDefn.SetWidth(14) 
fieldDefn.SetPrecision(6)
inlyr.CreateField(fieldDefn)
Run Code Online (Sandbox Code Playgroud)

  • 要关闭文件,建议使用`infile = None` (2认同)