Installation
pip install pyshp
Introduction
import shapefile
Read
sf=shapefile.Reader("{pathname} ",encoding='utf-8') # Only read
shapes and shape
shapes=sf.shapes() The return value is a list containing all the "geometry" in the file Data" object
shape=sf.shape(0) Shape is the first "geometric data" object
shapeType returns the collection type
returns The data type attribute of the first object
几何类型 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 Returns the data range
shape.bbox Returns the data range of the first collection object (x, y in the lower left corner coordinates and the x, y coordinates of the upper right corner)
points All coordinate points
shape.points Returns all coordinate points of the first collection object
parts Returns the coordinates of the first point of the "block"
shape.parts Returns the coordinates of the first point of each "block" of the first object
records and record
Get the attribute list
records
Get the attribute list, it is a function
sf. records();
The returned value is a list
record
Get a piece of data
sf.record(0)
The returned value is class
shapeRecords
Get record and shape at the same time
# 同时读取geometry and records sf.shapeRecords() 获取所有 red=sf.shapeRecords()[0] #获取第一条数据 print(red.record) #获取record print(red.shape) #获取shape
fields
Get shp file attribute field
print(sf.fields) [('DeletionFlag', 'C', 1, 0), ['OBJECTID', 'N', 9, 0], ['BSM', 'C', 12, 0], ['PXZQDM', 'C', 2, 0], ['PXZQMC', 'C', 50, 0]]
Write
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)创建点 if i % 2 == 0: arr.append([float(str[i]), float(str[i + 1])]) return arr fileWrite = shapefile.Writer("create/1.shp",encoding='utf-8') # 新建数据存放位置 # 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 写入面,点线面使用不同函数 fileWrite.poly([arr]) # 第二步:塞入属性值 fileWrite.record(str(i), '地块') # 保存结束 fileWrite.close()
The above is the detailed content of How to use pyshp to read and write shp files in python. For more information, please follow other related articles on the PHP Chinese website!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
