本文主要介绍「如何将 csv 格式的 POI 数据(亦可是其他空间点数据)批量转换为 shapefile 」,用于ArcGIS 空间可视化。主要用到 pyshp 库,这篇文章有该库的相关基础操作。
代码在 Python3.8 环境下运行。
代码实例
import shapefile
import csv
import os
Path = 'csv 数据源文件夹路径'
writePath = '保存 shp 的目标文件夹路径'
file_list = os.listdir(Path)
for readPath in file_list:
# 获得源数据的文件名
file = readPath.split(".")
print(file[0])
# 根据源数据命名新建 shapefile
writeFilePath = writePath + file[0] + ".shp"
file_dir = os.path.join(Path, readPath)
if __name__ == '__main__':
# 写入文件
w = shapefile.Writer(writeFilePath)
with open(file_dir, 'r', encoding='utf-8') as myFile:
myReader = csv.reader(myFile)
i = 0
for r in myReader:
if i == 0:
# 此部分参照[官方文档](https://pypi.org/project/pyshp/)获得代号属性,在代码结束后有相关说明
w.field('name', 'C', 100)
w.field('type', 'C', 100)
w.field('address', 'C', 100)
w.field('province', 'C', 100)
w.field('city', 'C', 100)
w.field('district', 'C', 100)
w.field('lng', 'F', 10, 5)
w.field('lat', 'F', 10, 5)
else:
w.point(float(r[9]), float(r[10]))
record = [r[0], r[1], r[2], r[3], r[4], r[5], float(r[9]), float(r[10])]
w.record(*record)
i = i + 1
print(file[0] + "_" + str(i))
# 激活自动平衡功能
w.autoBalance = 1
# 关闭写操作
w.close()
#【添加字段代号】
#Field type: the type of data at this column index. Types can be:
#"C": Characters, text.
# "N": Numbers, with or without decimals.
# "F": Floats (same as "N").
# "L": Logical, for boolean True/False values.
# "D": Dates.
# "M": Memo, has no meaning within a GIS and is part of the xbase spec instead.
注意
使用 pyshp 库创建的 shapefile 没有投影坐标系,也没有在库中找到相关的方法能够定义投影,故在生成 shapefile 后使用 Arcpy 进行批量投影。
代码参考自此文章,内容有部分修改。