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



but still cannot get it work.

An example of my data file, test.csv:


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.

  • 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? – Michael Stimson Sep 1 '15 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 Sep 1 '15 at 1:08
  • No error messages. It just doesn't pass the isValid test. – andrew Sep 1 '15 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. – Michael Stimson Sep 1 '15 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. – Germán Carrillo Sep 1 '15 at 3:13

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, privacy policy and cookie policy

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