python ogr_Python+OGR库学习(三):将含有字段值的TXT文件写入shpfile
代碼任務(wù)
已知有一個(gè)TXT文件,每行格式:country_name:X1 Y1,X2 Y2,…Xn,Yn,其中,Xn,Yn指折點(diǎn)坐標(biāo),把它導(dǎo)出為shp文件,TXT如下:
代碼思路
1、導(dǎo)入相關(guān)庫(kù)包,切換到當(dāng)前文件夾
2、注冊(cè)驅(qū)動(dòng),創(chuàng)建矢量文件,獲取圖層
3、創(chuàng)建輸出文件,并獲取圖層(沒(méi)有屬性定義)
4、定義輸出圖層字段屬性:
(1)TXT文件中只能得到一個(gè)字段,命名為name,設(shè)置屬性
(2)打開(kāi)TXT,讀取遍歷每一行:
創(chuàng)建ring類(lèi)型geom,分割每行內(nèi)容為兩部分(name和x,y值),將這行所有x,y值添加為ring坐標(biāo)點(diǎn)
創(chuàng)建polygon,將含有坐標(biāo)的ring添加進(jìn)去構(gòu)成一個(gè)polygon
創(chuàng)建這一行對(duì)應(yīng)的一個(gè)要素,并寫(xiě)入name字段值
要素寫(xiě)入圖層
清除此循環(huán)中ring、polygon及feature緩存,便于下次循環(huán)
(3)清除DataSource并關(guān)閉TXT文件
關(guān)鍵點(diǎn)
每行創(chuàng)建一個(gè)要素
polygon創(chuàng)建思路:ring-addpoint to ring -polygon–addring to polygon
split分割字段和坐標(biāo)點(diǎn)
代碼
#導(dǎo)入相關(guān)庫(kù)包
import osgeo,gdal,os,ogr,osr
#創(chuàng)建輸出shp
driver = ogr.GetDriverByName('ESRI Shapefile')
os.chdir(r'F:\PQ\python_exercise\7weeks數(shù)據(jù)\ospy_data2\ospy_data2')
if os.path.exists('country.shp'):
driver.DeleteDataSource('country.shp')
outds = driver.CreateDataSource('country.shp')
if outds == None:
print('創(chuàng)建文件失敗!')
#創(chuàng)建圖層
dst_osr = osr.SpatialReference()
dst_osr.ImportFromEPSG(4326)
outlayer = outds.CreateLayer('country',dst_osr,geom_type = ogr.wkbPolygon)
#設(shè)置字段屬性
fieldDefn = ogr.FieldDefn('name',ogr.OFTString)
fieldDefn.SetWidth(50)
#圖層創(chuàng)建屬性
outlayer.CreateField(fieldDefn)
#讀取要素統(tǒng)一屬性
featuredefn = outlayer.GetLayerDefn()
#讀取TXT
txtfile = open('ut_counties.txt','r')
#print(txtfile)
#遍歷每一行,對(duì)每一行創(chuàng)建一個(gè)要素,創(chuàng)建polygon對(duì)象,寫(xiě)入對(duì)象及屬性
for line in txtfile:
#print(line)
#創(chuàng)建polygon對(duì)象的ring
ring = ogr.Geometry(ogr.wkbLinearRing)
#獲取TXT中的點(diǎn)坐標(biāo),用于ring的坐標(biāo)點(diǎn)
tmp = line.split(':')
name = tmp[0]
coords = tmp[1]
coordslist = coords.split(',')#得到坐標(biāo)點(diǎn)對(duì)
print(coordslist)
for coord in coordslist:
xy = coord.split()#獲取坐標(biāo)點(diǎn)
x = float(xy[0])
y = float(xy[1])
#給ring添加點(diǎn)坐標(biāo)
ring.AddPoint(x,y)
#創(chuàng)建polygon對(duì)象
polygon = ogr.Geometry(ogr.wkbPolygon)
polygon.AddGeometry(ring)
#創(chuàng)建要素(使用要素統(tǒng)一屬性),寫(xiě)入幾何圖形,字段屬性
feature = ogr.Feature(featuredefn)
feature.SetGeometry(polygon)
feature.SetField('name',name)
#要素寫(xiě)入圖層
outlayer.CreateFeature(feature)
#每次寫(xiě)入完,銷(xiāo)毀ring,polygon和feature
ring.Destroy()
polygon.Destroy()
feature.Destroy()
#TXT文件關(guān)閉和DataSource清除
txtfile.close()
outds.Destroy()
結(jié)果
學(xué)習(xí)使用,如有意見(jiàn),感謝指正*
轉(zhuǎn)載自:https://blog.csdn.net/weixin_42924891/article/details/85333559
總結(jié)
以上是生活随笔為你收集整理的python ogr_Python+OGR库学习(三):将含有字段值的TXT文件写入shpfile的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c语言的int型运算符,C语言运算符
- 下一篇: python调用各个分词包