Reputation: 1440
I am attempting to import a file into QGIS using a python script. I'm having a problem getting it to accept the CRS. Code so far
from PyQt4.QtGui import * from PyQt4.QtCore import * from qgis.core import * from qgis.utils import iface
InFlnm='Input.CSV'
InDrPth='G:/test'
InFlPth="file:///"+InDrPth+InFlnm
uri = InFlPth+"?delimiter=%s&xField=%s&yField=%s" % (",","x","y")
bh = QgsVectorLayer(uri, InFlnm, "delimitedtext")
QgsMapLayerRegistry.instance().addMapLayer(bh)
Now all the above works OK and QGIC prompts me for a CRS before executing the last line of the script to display the layer - as long as I comment-out step 6
However, if a attempt to set the CRS removing ### from step 6 I get a syntax error reporting on the last line that displays the points (Step 7). Note sure what the trick is here - I'm pretty new to Python but know my way around some other programming lagnuages
Upvotes: 4
Views: 10092
Reputation: 1440
I found the answer to the final part of the problem at http://www.purplelinux.co.nz/. I seems you need to suppress the form that prompts for the CRS. So the my script now looks like
#--- 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 )
The imported points now display but I'm getting an error stating that the CRS is not recognised so suspect step 9 above is not working. I will post again if I can crack this problem otherwise I may have to be happy with the CRS default perhaps.
Upvotes: 4
Reputation: 41
Thanks for the import example, really helpful for a geocoder python script I want to output a csv from into qgis. To solve your problem, add the crs in your uri line:
uri = InFlPth+"?crs=epsg:32365&delimiter=%s&xField=%s&yField=%s" % (",","x","y")
Upvotes: 3
Reputation: 3781
There is a parenthesis missing from the end of your --6 line of code.
Upvotes: 2