1. 安装依赖
Win + R进入cmd,安装依赖geopandas及tk
pip install geopandas -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install tk -i https://pypi.tuna.tsinghua.edu.cn/simple/
2. 批量shp转geojson代码
2.1 引入依赖包
import geopandas as gpd
import sys
import os
from tkinter import messagebox #引入消息框
2.2 使用提示
messagebox.showinfo('提示','将shp数据放入当前*.py所在文件夹')
2.3 获取py所在路径,定义为shp输入路径及geojson输出路径
path = os.path.abspath(os.path.dirname(sys.argv[0])) #获取当前py文件所在目录
# 设置工作目录,即存放shp文件的文件夹路径
input_dir = path + "/input"
output_dir = path + "/output"
2.4 读取所有*.shp文件,批量将*.shp转为*.geojson同名文件,注意设置格式driver及编码encoding
# 获取所有shp文件的文件名
shp_files = [file for file in os.listdir(input_dir) if file.endswith('.shp')]
# 遍历每个shp文件,转换成geojson
for shp_file in shp_files:
# 读取shp文件
gdf = gpd.read_file(os.path.join(input_dir, shp_file))
# 设定输出geojson文件的文件名,将.shp后缀改成.geojson
geojson_file = shp_file.replace('.shp', '.geojson')
# 将GeoDataFrame对象写入geojson文件
gdf.to_file(os.path.join(output_dir, geojson_file), driver='GeoJSON',encoding="utf-8")
2.5 转换完成给出消息提示的两种方法(print和message)
#print('转换完成')
messagebox.showinfo('提示','转换完成!') #弹出消息框提示
2.6 批量shp转geojson完整代码
import geopandas as gpd
import sys
import os
from tkinter import messagebox #引入消息框
messagebox.showinfo('提示','将shp数据放入当前*.py所在文件夹')
#path = os.getcwd()#获取当前编辑器路径,仅限python编辑器,用notepad++则为npp路径
path = os.path.abspath(os.path.dirname(sys.argv[0])) #获取当前py文件所在目录
# 设置工作目录,即存放shp文件的文件夹路径
input_dir = path + "/input"
output_dir = path + "/output"
# 获取所有shp文件的文件名
shp_files = [file for file in os.listdir(input_dir) if file.endswith('.shp')]
# 遍历每个shp文件,转换成geojson
for shp_file in shp_files:
# 读取shp文件
gdf = gpd.read_file(os.path.join(input_dir, shp_file))
# 设定输出geojson文件的文件名,将.shp后缀改成.geojson
geojson_file = shp_file.replace('.shp', '.geojson')
# 将GeoDataFrame对象写入geojson文件
gdf.to_file(os.path.join(output_dir, geojson_file), driver='GeoJSON',encoding="utf-8")
#print('转换完成')
messagebox.showinfo('提示','转换完成!') #弹出消息框提示
#geojson转shp,只需要将代码中shp字样与geojson字样互相替换即可,注意driver="ESRI Shapefile"
3. 批量geojson转shp代码
批量geojson转shp,只需要将代码中shp字样与geojson字样对调,注意修改输出格式driver="ESRI Shapefile"即可
4. 使用说明
将shp或geojson文件放入*.py所在文件夹,运行该py文件即可实现转换