簡體   English   中英

使用Python將csv導入QGIS

[英]Import csv into QGIS using Python

我正在嘗試使用python腳本將文件導入QGIS。 我在接受CRS時遇到了問題。 代碼到目前為止

來自PyQt4.QtGui import * from PyQt4.QtCore import * from qgis.core import * from qgis.utils import iface

---- 1在此處設置文件名

InFlnm = 'Input.CSV'

--- 2在此處設置路徑名

InDrPth = 'G:/測試'

--- 3為uri構建文件名和路徑

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

--- 4設置導入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步

但是,如果嘗試從步驟6中設置CRS刪除###,則會在顯示這些點的最后一行上收到語法錯誤報告(步驟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默認值感到滿意。

感謝導入示例,對於geocoder python腳本非常有用,我想將csv輸出到qgis中。 要解決您的問題,請在您的uri行中添加crs:

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

在你的-6行代碼的末尾有一個括號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM