首页 > 编程语言 >python读取shapefile

python读取shapefile

时间:2023-08-23 12:12:06浏览次数:41  
标签:layer 读取 python reclist shapefile fd fieldlist file spatialref

 

#!/usr/bin/env python
# coding: utf-8
# Autor GaoSong
# 读取shp数据

import os
import tkinter
import tkinter.messagebox
import tkinter.filedialog
from osgeo import gdal
from osgeo import osr
from osgeo import ogr
from osgeo import gdalconst


class ARCVIEW_SHAPE:
    #------------------------------
    #read shape file
    #------------------------------
    def read_shp(self,file):
        #open
        ds = ogr.Open(file,False) #False - read only, True - read/write
        layer = ds.GetLayer(0)
        #layer = ds.GetLayerByName(file[:-4])
        #fields
        lydefn = layer.GetLayerDefn()
        spatialref = layer.GetSpatialRef()
        #spatialref.ExportToProj4()
        #spatialref.ExportToWkt()
        geomtype = lydefn.GetGeomType()
        fieldlist = []
        for i in range(lydefn.GetFieldCount()):
            fddefn = lydefn.GetFieldDefn(i)
            fddict = {'name':fddefn.GetName(),'type':fddefn.GetType(),
                      'width':fddefn.GetWidth(),'decimal':fddefn.GetPrecision()}
            fieldlist += [fddict]
        #records
        geomlist = []
        reclist = []
        feature = layer.GetNextFeature()
        while feature is not None:
            geom = feature.GetGeometryRef()
            geomlist += [geom.ExportToWkt()]
            rec = {}
            for fd in fieldlist:
                rec[fd['name']] = feature.GetField(fd['name'])
            reclist += [rec]
            feature = layer.GetNextFeature()
        #close
        ds.Destroy()
        return (spatialref,geomtype,geomlist,fieldlist,reclist)

    #------------------------------
    #write shape file
    #------------------------------
    def write_shp(self,file,data):
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES")
        gdal.SetConfigOption("SHAPE_ENCODING","UTF-8")
        spatialref,geomtype,geomlist,fieldlist,reclist = data
        #create
        driver = ogr.GetDriverByName("ESRI Shapefile")
        if os.access(file, os.F_OK ):
            driver.DeleteDataSource(file)
        ds = driver.CreateDataSource(file)
        #spatialref = osr.SpatialReference( 'LOCAL_CS["arbitrary"]' )
        #spatialref = osr.SpatialReference().ImportFromProj4('+proj=tmerc ...')
        layer = ds.CreateLayer(file[:-4],srs=spatialref,geom_type=geomtype)
        # print type(layer)
        #fields
        for fd in fieldlist:
            field = ogr.FieldDefn(fd['name'],fd['type'])
            if fd.has_key('width'):
                field.SetWidth(fd['width'])
            if fd.has_key('decimal'):
                field.SetPrecision(fd['decimal'])
            layer.CreateField(field)
        #records
        for i in range(len(reclist)):
            geom = ogr.CreateGeometryFromWkt(geomlist[i])
            feat = ogr.Feature(layer.GetLayerDefn())
            feat.SetGeometry(geom)
            for fd in fieldlist:
                # print(fd['name'],reclist[i][fd['name']])
                feat.SetField(fd['name'],reclist[i][fd['name']])
            layer.CreateFeature(feat)
        #close
        ds.Destroy()


if __name__ == '__main__':
    activeShp = ARCVIEW_SHAPE()
    spatialref,geomtype,geomlist,fieldlist,reclist= activeShp.read_shp('./HSCSD/HSCSD.shp')
    print("spatialref:",spatialref)
    print("geomtype:",geomtype)
    print("geomlist:",geomlist)
    print("fieldlist:",fieldlist)
    print("reclist:",reclist)

 

标签:layer,读取,python,reclist,shapefile,fd,fieldlist,file,spatialref
From: https://www.cnblogs.com/jsbs/p/17650859.html

相关文章

  • python获取网络时间和本地时间
    今天我们来看一下如何用python获取网络时间和本地时间,直接上代码吧,代码中都有注释。python获取网络时间1234567891011121314151617181920212223242526272829获取网络时间def getBeijinTime():"""获取北京时间"""try:conn= httplib.HTTPConnection("www.beijing-time.org")co......
  • Python基础入门学习笔记 070 GUI的终极选择:Tkinter7
    实例1:添加Tags1fromtkinterimport*23root=Tk()4text=Text(root,width=30,height=5)5text.pack()67#INSERT索引表示插入光标当前的位置8text.insert(INSERT,"IloveFishC.com!")#光标当前的位置插入9#注意,行号从1开始,列号则从0开始10text.ta......
  • Python中的if-else语法糖
    Python中的if语句是用于条件控制的一种语法结构,可以根据条件的真假来决定程序的执行路径。在Python中,if语句的语法如下:if条件:执行语句块其中,条件是一个返回布尔值的表达式,如果条件为True,那么执行语句块中的代码;如果条件为False,则跳过语句块。除了基本的if语句外,Python还......
  • Python基础入门学习笔记 067 GUI的终极选择:Tkinter4
    实例1:1fromtkinterimport*23root=Tk()#创建主窗口4e=Entry(root)#在主窗口中插入输入框5e.pack(padx=20,pady=20)67e.delete(0,END)#清空输入框8e.insert(0,"默认文本...")#设置输入框内容910mainloop() 实例2:1fromtkinterimp......
  • Python基础入门学习笔记 068 GUI的终极选择:Tkinter5
    Listbox组件如果需要提供选项给用户选择,单选可以用Radiobutton组件,多选可以用Checkbutton,如果提供的选项非常多,可以考虑使用Listbox组件。Listbox是以列表的形式显示出来,并支持滚动条操作。实例1:1fromtkinterimport*23root=Tk()#创建主窗口45theLB=Listb......
  • Python基础入门学习笔记 069 GUI的终极选择:Tkinter6
    Text组件Text(文本)组件用于显示和处理多种任务。虽然该组件的主要目的是显示多行文本,但它常常也被用于作为简单的文本编辑器和网页浏览器使用。实例1:插入内容1fromtkinterimport*23root=Tk()4text=Text(root,width=30,height=2)5text.pack()6#INSERT......
  • Python基础入门学习笔记 066 GUI的终极选择:Tkinter3
    实例1:Checkbutton组件1fromtkinterimport*23root=Tk()4#需要一个Tkinter变量,用于表示该按钮是否被选中5v=IntVar()6c=Checkbutton(root,text="测试一下",variable=v)78c.pack()9#如果被选中,那么变量v被赋值为1,否则为010#可以用个Label......
  • Pybind11:使用C++编写Python模块
    放假摆了一周了。看论文实在不是什么有意思的活。这两天研究了一下Pybind11的用法。使用C/C++和Python混合编程的想法很早就有了,在大一的一次比赛时曾经实践过(虽然不是我写的),当时获得了比较显著的性能提升。但是当时用的是Swig,据队友说Swig对于NumPy的支持极为阴间,当时调试花了好......
  • Python基础入门学习笔记 064 GUI的终极选择:Tkinter
    >>>importtkinter #Tkinter是python默认的GUI库,导入Tkinter模块>>> 实例1:1importtkinterastk23root=tk.Tk()#创建一个主窗口,用于容纳整个GUI程序4root.title("FishCDemo")#设置主窗口对象的标题栏56#添加一个Label组件,可以显示文本、图标或者图......
  • Python基础入门学习笔记 065 GUI的终极选择:Tkinter2
    实例1:Label组件显示文字与gif图片1#导入tkinter模块的所有内容2fromtkinterimport*34#创建主窗口5root=Tk()6#创建一个文本Label对象,文字为左对齐,离左边边框距离为107textLabel=Label(root,8text="您下载的影片含有未成年人......