使用Python将csv导入QGIS

2024-05-29 07:42:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python脚本将文件导入QGIS。我很难让它接受CRS。迄今为止的代码

从PyQt4.QtGui导入* 从PyQt4.QtCore导入* 从qgis.core导入* 从qgis.utils导入iface

----1在此处设置文件名

InFlnm='输入.CSV'

---2在此处设置路径名

InDrPth='G:/测试'

---3生成uri的文件名和路径

InFlPth=“文件:///”+InDrPth+InFlnm

---4套进口刺这里注只需设置x和y其他人来免费!

uri=InFlPth+“?分隔符=%s&xField=%s&yField=%s“%(”,“,”x“,”y“)

---5将点加载到层中

bh=QgsVectorLayer(uri,InFlnm,“delimitedtext”)

---6设置CRS(不确定这是否有效?)

bh.setCrs(QgsCoordinateReferenceSystem(32365,QgsCoordinateReferenceSystem.epsgsrsid)

---7在QGIS中显示图层(这里我得到一个语法错误?)

QgsMapLayerRegistry.instance().addMapLayer(bh)

现在,上面的所有操作都正常,QGIC在执行脚本的最后一行以显示层之前提示我输入CRS—只要我注释掉步骤6

但是,如果试图设置CRS,从步骤6中删除#########,则在显示点的最后一行会收到语法错误报告(步骤7)。请注意这里的诀窍是什么-我对Python还很陌生,但我知道如何绕过其他一些编程缺陷


Tags: 文件脚本文件名步骤uribhpyqt4语法错误
3条回答

我在http://www.purplelinux.co.nz/找到了问题最后部分的答案。我觉得你需要取消提示输入CRS的表单。所以我的剧本现在看起来

#--- Load a csv file and set CRS
#---1 Reference library
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface

#---  2 Turn of the CRS dialog box
s = QSettings()
oldValidation = s.value( "/Projections/defaultBehaviour")
s.setValue( "/Projections/defaultBehaviour", "useGlobal" )

#--- 3 Set file name here
InFlnm='Test.csv'

#--- 4  Set pathname here
InDrPth='C:/_Work/PyQGIS/Test/'

#--- 5 Build file name an path for uri
InFlPth="file:///"+InDrPth+InFlnm

#---  6 Set import Sting here note only need to set x and y other come for free
uri = InFlPth+"?delimiter=%s&xField=%s&yField=%s" % (",","x","y")

#--- 7 Load point layer
bh = QgsVectorLayer(uri, InFlnm, "delimitedtext")

#--- 8 Confirm something is loaded and valid
bh.isValid()

#--- 9 Set CRS
bh.setCrs(QgsCoordinateReferenceSystem(32365, QgsCoordinateReferenceSystem.EpsgCrsId))

#--- 10 Display the layer into QGIS (but it asks for CRS before displaying_
QgsMapLayerRegistry.instance().addMapLayer(bh)

#--- 11 turn CRS dialog box back on again
s.setValue( "/Projections/defaultBehaviour", oldValidation )

导入的点现在显示,但我收到一个错误,指出CRS无法识别,因此怀疑上面的步骤9不起作用。如果我能解决这个问题,我会再次发帖,否则我可能会对CRS的违约感到满意。

感谢导入示例,这对geocoder python脚本非常有帮助,我希望将csv输出到qgis中。要解决问题,请在uri行中添加crs:

uri = InFlPth+"?crs=epsg:32365&delimiter=%s&xField=%s&yField=%s" % (",","x","y")    

--6行代码的末尾缺少一个括号。

相关问题 更多 >

    热门问题