版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
版权
GIS专栏收录该内容
2 篇文章0 订阅
订阅专栏
在GIS项目中经常需要将csv转为shp文件,或者需要将shp文件转化为csv文件,本项目基于python实现。话不多说,直接上代码。
1.shp转csv:
#shp属性表转化为excel
import shapefile # 使用pyshp库
from pandas.core.frame import DataFrame
import os
def shp_to_excel(shp_path,out_path):
file = shapefile.Reader(shp_path,encoding = 'gbk')
shapes = file.shapes()
#
print(file.shapeType) # 输出shp类型
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(file.bbox) # 输出shp的范围
#
print(shapes[1].parts)
print(len(shapes)) # 输出要素数量
print(file.numRecords) # 输出要素数量
print(file.records()) # 输出所有属性表
#
字段类型:此列索引处的数据类型。类型可以是:
“C”:字符,文字。
“N”:数字,带或不带小数。
“F”:浮动(与“N”相同)。
“L”:逻辑,表示布尔值True / False值。
“D”:日期。
“M”:备忘录,在GIS中没有意义,而是xbase规范的一部分。
fields = file.fields
for index in range(len(shapes)):
geometry = shapes[index]
file = file.records()
data=DataFrame(file)
data.to_excel(out_path)
for root,dirs,files in os.walk(r"E:SHP文件夹"):
for file in files:
# print(os.path.join(root,file))
if os.path.join(root,file).split('\\')[-1].split('.')[-1] == 'shp':
print(os.path.join(root,file))
shp_path = os.path.join(root,file)
out_path = r'E:excel文件夹\\'+\
os.path.join(root,file).split('\\')[-1].split('.')[0] +'.xlsx'
shp_to_excel(shp_path,out_path)
2.csv转shp:
import arcpy
import os
import multiprocessing
def process_csv_file(param):
multiprocessing function to process csv files
:param param: workspace and csv file information
:return: shp file path
try:
arcpy.env.workspace = param.get('workspace')
csv_file = param.get('file')
print 'Processing: {}'.format(csv_file)
arcpy.env.overwriteOutput = True
shpfile = os.path.splitext(csv_file.replace('-', '_'))[0]
temp_path = os.path.join('in_memory', ''.join([shpfile, '_EventLayer']))
spatialreference = "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision"
evt_lyr = arcpy.MakeXYEventLayer_management(csv_file, "lon", "lat", temp_path, spatialreference)
arcpy.CopyFeatures_management(evt_lyr, shpfile)
del evt_lyr
return os.path.join(param.get('workspace'), shpfile)
except Exception as error:
return error
def main():
""" main function """
try:
# path of csv files and shape files to keep
workspace = r"D:\model2\csv_to_shp\201result"
# Number of files to process at a time
process = 4
params = [{'workspace': workspace, 'file': file_name} for file_name in os.listdir(workspace)
if file_name.endswith('.csv')]
pool = multiprocessing.Pool(processes=process)
result = pool.map_async(process_csv_file, params)
pool.close()
pool.join()
print result
except Exception as error:
# If an error occurred print the message to the screen
print error
if __name__ == '__main__':
main()