pyQgis一次性将多个txt坐标文件转为shp文件
时间: 2023-08-07 07:08:27 浏览: 415
可以使用以下代码,使用pyQGIS一次性将多个txt坐标文件转为shp文件:
```python
import os
from qgis.core import QgsVectorLayer, QgsCoordinateReferenceSystem, QgsFields, QgsField, QgsWkbTypes, QgsGeometry, QgsVectorFileWriter
# 设置txt文件所在的文件夹路径和shp文件保存的路径
txt_folder = '/path/to/txt/folder'
shp_file = '/path/to/output/shp/file.shp'
# 定义坐标系
crs = QgsCoordinateReferenceSystem('EPSG:4326')
# 遍历txt文件夹中的所有txt文件
for filename in os.listdir(txt_folder):
if filename.endswith('.txt'):
txt_file = os.path.join(txt_folder, filename)
# 打开txt文件并读取坐标数据
with open(txt_file, 'r') as f:
data = f.readlines()
x_values = [float(line.split(',')[0]) for line in data]
y_values = [float(line.split(',')[1]) for line in data]
# 创建shp文件并写入坐标数据
fields = QgsFields()
fields.append(QgsField('id', QVariant.Int))
writer = QgsVectorFileWriter(shp_file, 'UTF-8', fields, QgsWkbTypes.Point, crs, 'ESRI Shapefile')
for i in range(len(x_values)):
point = QgsGeometry.fromPointXY(QgsPointXY(x_values[i], y_values[i]))
feature = QgsFeature()
feature.setGeometry(point)
feature.setAttributes([i])
writer.addFeature(feature)
del writer
```
注意修改代码中的文件夹路径和文件名,以及根据需要修改坐标系和字段属性。
阅读全文