python连接postgis导出为shp
时间: 2024-10-16 08:08:50 浏览: 32
在Python中,可以使用` Fiona` 和 `psycopg2` 这两个库来连接PostGIS数据库并导出数据到Shapefile(.shp)文件。以下是基本步骤:
1. 首先,确保已经安装了所需的库。你可以通过pip安装它们:
```bash
pip install psycopg2-binary fiona shapely
```
2. 导入库并建立数据库连接:
```python
import psycopg2
from fiona.crs import from_epsg
from shapely.geometry import shape
# 数据库连接信息
conn_str = "dbname='your_database' user='your_username' host='localhost' password='your_password'"
conn = psycopg2.connect(conn_str)
```
3. 使用SQL查询获取数据:
```python
sql_query = "SELECT * FROM your_table WHERE some_condition;"
cur = conn.cursor()
rows = cur.execute(sql_query)
features = [(row[0], row[1]) for row in rows] # 假设前两列是几何字段和属性列
```
4. 创建一个输出的 Shapefile 的元数据文件(`.prj`, `.shx`, `.dbf` 等):
```python
crs = from_epsg(4326) # 或者你的坐标系ID,例如4326是WGS84
schema = {
'geometry': 'Polygon',
'properties': {f'field_{i}': 'str' for i in range(len(features[0][1]))}
}
with env():
with MemoryFile() as memfile:
with memfile.open(driver='ESRI Shapefile', schema=schema, crs=crs) as dst:
for feature_id, props in enumerate(features):
geom = shape(props[0])
dst.write({
'geometry': geom,
'properties': dict(zip(dst.schema['properties'].keys(), props[1]))
})
```
5. 将内存中的数据写入磁盘上的 Shapefile 文件:
```python
output_shp_path = 'output.shp'
memfile.to_file(output_shp_path)
```
6. 关闭连接:
```python
conn.close()
```
阅读全文