4

I am having trouble loading csv files into layers using QgsVectorLayer().

I know this looks like a repeat, but I have carefully read

Create a script to add delimited text layer in QGIS

and

http://hub.qgis.org/issues/7491

but still cannot get it work.

An example of my data file, test.csv:

Index,y,x
0,37.7646618,-122.4960858
1,37.777494,-122.416311
2,37.717707,-122.3997056
3,37.732284,-122.498118
4,37.749998,-122.392333

My code:

import os
import urllib

import pathlib
from qgis.core import QgsVectorLayer

local_path = 'C:\dev\FCMS_conflation\data\TMC_nodes.csv'
node_layer = 'test'

abspath = os.path.abspath(local_path)
params = {'delimiter': ',',
          'decimalPoint': '.',
          'xField': longitude,
          'yField': latitude}

uri = "%s?%s" %(pathlib.Path(abspath).as_uri(), urllib.unquote(urllib.urlencode(params)))

layer = QgsVectorLayer(uri, node_layer, "delimitedtext")

The formatted URI looks like:

[] uri
>>> 'file:///C:/dev/FCMS_conflation/data/TMC_nodes.csv?decimalPoint=.&delimiter=,&xField=longitude&yField=latitude'

I have tried many variations of the parameters, including the crs and type. But no matter what I try, I cannot create a valid layer.

[] layer.isValid()
>>> False

I have verified that I can add the file using the QGIS gui. I even tried using the uri provided by layer.metadata from within the Python plugin.

I am using QGIS 2.10.1 on Windows 7 64-bit machine.

6
  • Good question, where does node_layer come from? It should be a Qstring but I can't see where it's being set. Are you getting any error message? Commented Sep 1, 2015 at 1:02
  • I defined node_layer to just be a random string. I edited the code snip. Maybe I need to make a Qstring?
    – andrew
    Commented Sep 1, 2015 at 1:08
  • No error messages. It just doesn't pass the isValid test.
    – andrew
    Commented Sep 1, 2015 at 1:10
  • 1
    You're in python, QString is near enough to string (C would have a cow about the subtle difference). Perhaps it's the path that's the difficulty.. the example given doesn't start with file:///, perhaps just c:/dev...?decimal... like in the example. Commented Sep 1, 2015 at 1:48
  • 2
    It seems you need to set the QGIS prefix path, as I explain in gis.stackexchange.com/questions/144058/… and gis.stackexchange.com/questions/155745/… Please let me know if it solves your problem. Commented Sep 1, 2015 at 3:13

1 Answer 1

5

It seems you need to set the QGIS prefix path, as I explain in Loading raster layer using PyQGIS? and Failed to create memory layers in QGIS application on Linux

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.