[GIS] Loading non-spatial data via CSV using PyQGIS for standalone script

csvpyqgispython-2.7

I am trying to load a .shp file, and a non-spatial data table .csv file. Then join the table to the shapefile. Both files have a primary key.

Here is my code:

countyLayer = QgsVectorLayer(countySHP, "County_Layer", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(countyLayer)

Loading the shapefile works fine:

table = QgsVectorLayer(inputFile, "table", "delimitedtext")
QgsMapLayerRegistry.instance().addMapLayer(table)

Loading the table returns "File cannot be opened or delimiter parameters are not valid" in the delimitedtext log in QGIS. I've tried adding the "?delimiter=;" to the end of the filename and what not still get same errors. These errors don't stop the code from running however.

processing.runandload('qgis:joinattributestable', countyLayer, table, 'AFFGEOID', 'GEO_ID','memory:layer')
joinedLayer = QgsMapLayerRegistry.instance().mapLayersByName('memory:layer')[0]

This next part actually works… even with the errors above. It creates and loads a new shapefile WITH the added attributes like I want it too. However, the table never appears in the layers panel, and when I populate a list of all layers in the map layer registry, only the two shapefiles are present and no table.

I'm fairly new to PyQGIS, so perhaps I am completely overlooking something.

Does the table get stored somewhere else and not the layers registry?

When I first encountered the problem I thought it was something to do with the 'processing.runandload', but when I comment that out, the table still never shows up in the layers panel. This is a stand alone script so I can't use any iface stuff. I just don't understand where this .csv is going. The cookbook has no information on loading delimited text without geographic data, so maybe there is another way to open it.

Best Answer

Try to reverse engineer (deduce from UI behaviour the expected parameters).

According to the return error, you have an issue with delimiter in your CSV data source before processing.

How can you do it?

You should try to go in Layers > Add Layer > Add Delimited Text Layer... and add your CSV file like below :

QGIS - Add Delimited Text layer dialog

You will be able to debug visually with this.

Then, go in your layer Properties and in tab General, look at Layer source. You should have similar result as the following image. You can from this, deduce additional arguments required to add your CSV layer with PyQGIS without issues.

Properties General tab for a delimited text layer

I forgot to mention additional information: the documentation of each parameters for Delimited Text Layer within the QGIS API is available from this QGIS API page (link for QGIS 2.14).

Related Question