python使用pyshp讀寫shp文件的實現(xiàn)
安裝
pip install pyshp
引入
import shapefile
讀取
sf=shapefile.Reader("{路徑名}",encoding='utf-8') # 僅僅讀取
shapes與shape
shapes=sf.shapes() 返回值是一個列表,包含該文件中所有的”幾何數(shù)據(jù)”對象
shape=sf.shape(0) Shape是第1個”幾何數(shù)據(jù)”對象
shapeType返回集合類型
返回第1個對象的數(shù)據(jù)類型屬性
幾何類型
NULL = 0
POINT = 1
POLYLINE = 3
POLYGON = 5
MULTIPOINT = 8
POINTZ = 11
POLYLINEZ = 13
POLYGONZ = 15
MULTIPOINTZ = 18
POINTM = 21
POLYLINEM = 23
POLYGONM = 25
MULTIPOINTM = 28
MULTIPATCH = 31
print(shape.shapeType)
bbox 返回數(shù)據(jù)范圍
shape.bbox 返回第一個集合對象的數(shù)據(jù)范圍(左下角的x,y坐標和右上角的x,y坐標)
points 所有坐標點
shape.points 返回第一個集合對象的所有坐標點
parts 返回’塊’的第一個點坐標
shape.parts 返回第一個對象的每個”塊”的第一個點坐標
records與record
獲取屬性列表
records
獲取屬性列表,是個函數(shù)
sf.records();
返回的值是個list
record
獲取一條數(shù)據(jù)
sf.record(0)
返回的值是class
shapeRecords
同時獲取record和shape
# 同時讀取geometry and records sf.shapeRecords() 獲取所有 red=sf.shapeRecords()[0] #獲取第一條數(shù)據(jù) print(red.record) #獲取record print(red.shape) #獲取shape
fields
獲取shp文件屬性字段
print(sf.fields)
[('DeletionFlag', 'C', 1, 0), ['OBJECTID', 'N', 9, 0], ['BSM', 'C', 12, 0], ['PXZQDM', 'C', 2, 0], ['PXZQMC', 'C', 50, 0]]寫入
import shapefile
outshp = 'a.shp'
?
?landlist=[ '84.60212,45.03658,84.60794,45.03938,84.61473,45.04151,84.62442,45.04375,84.62727,45.03632,84.63939,45.0367,84.64906,45.03277,84.63886,45.02233',
? ? '84.58063,45.05523,84.57974,45.04717,84.59864,45.04792,84.60078,45.05523,84.58758,45.05473,84.58223,45.05523'
]
def tramform(lat_lng):
? ? str =lat_lng
? ? str = str.split(',')
? ? arr = []
? ? for i in range(len(str) - 1):
? ? ? ? # 第一列,第二列作為經緯度(x,y)創(chuàng)建點
? ? ? ? if i % 2 == 0:
? ? ? ? ? ? arr.append([float(str[i]), float(str[i + 1])])
? ? return arr
fileWrite = shapefile.Writer("create/1.shp",encoding='utf-8') ?# 新建數(shù)據(jù)存放位置
# shp文件屬性字段 Fid,Shape會自動生成。
fileWrite.field('landid')
fileWrite.field('landName')
for i in range(len(landlist)):
? ? # 第一步:塞入形狀
? ? ## 這個形狀指的就是那些點的集合
? ? ## 由于源碼中要求的輸入是列表,因此就算只塞入一個,也要套一個列表
? ? arr=[]
? ? arr=tramform(landlist[i])
? ? #[[84.60212, 45.03658], [84.60794, 45.03938], [84.61473, 45.04151], [84.62442, 45.04375], [84.62727, 45.03632], [84.63939, 45.0367], [84.64906, 45.03277], [84.63886, 45.02233]]
? ? #poly 寫入面,點線面使用不同函數(shù)
? ? fileWrite.poly([arr])
? ? # 第二步:塞入屬性值
? ? fileWrite.record(str(i), '地塊')
# 保存結束
fileWrite.close()到此這篇關于python使用pyshp讀寫shp文件的實現(xiàn)的文章就介紹到這了,更多相關pyshp讀寫shp內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

