我正在尝试使用 python 脚本将文件导入 QGIS。我在让它接受 CRS 时遇到问题。到目前为止的代码
从 PyQt4.QtGui 导入 * 从 PyQt4.QtCore 导入 * 从 qgis.core 导入 * 从 qgis.utils 导入 iface
----1 在此设置文件名
InFlnm='输入.CSV'
---2 在这里设置路径名
InDrPth='G:/test'
---3 构建uri的文件名和路径
InFlPth="文件:///"+InDrPth+InFlnm
---4 设置import Sting 这里注意只需要设置x和y 其他的免费来!
uri = InFlPth+"?delimiter=%s&xField=%s&yField=%s"% (",","x","y")
---5 将点加载到图层中
bh = QgsVectorLayer(uri, InFlnm, "delimitedtext")
---6 设置 CRS(不确定这是否有效?)
bh.setCrs(QgsCoordinateReferenceSystem(32365, QgsCoordinateReferenceSystem.EpsgCrsId)
---7 在QGIS中显示图层(这里语法错误?)
QgsMapLayerRegistry.instance().addMapLayer(bh)
现在以上所有工作正常,QGIC 在执行脚本的最后一行以显示图层之前提示我输入 CRS - 只要我注释掉第 6 步
但是,如果尝试设置 CRS 从步骤 6 中删除###,我会在显示点的最后一行(步骤 7)上收到语法错误报告。请注意这里的诀窍是什么——我是 Python 的新手,但知道如何解决其他一些编程问题
最佳答案
我在 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 默认设置感到满意。
关于python - 使用 Python 将 csv 导入 QGIS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27033261/