Search code examples
pythonqgis

Errors in import multiple csv files into QGIS


I want to import multiple csv files into QGIS 3.2. It shows that "TypeError: QgsProject.addMapLayers(): argument 1 has unexpected type 'QgsVectorLayer'". I am new to QGIS and get confused. Here is my code. Thanks in advance!

import os, glob
path_to_csv = "D:/Paper/Data/bga_new_coord/"
os.chdir(path_to_csv)

for fname in glob.glob('*.csv'):
    uri = "file:///" + path_to_csv + fname + "?delimiter={}&crs=epsg:28355&xField={}&yField={}".format(";","xcoord","ycoord")
    name=fname.replace('.csv', '')
    lyr=QgsVectorLayer(uri, name, 'delimitedtext')
    lyr.isValid()
    QgsProject.instance().addMapLayers(lyr)

And the Error is

TypeError: QgsProject.addMapLayers(): argument 1 has unexpected type 'QgsVectorLayer'

Solution

  • You are using the function addMapLayers() which expects a list of layers (ref) instead of a single layer. Instead, try using addMapLayer() , which expects a layer.

    The error you get says basically the same thing: "Unexpectedly, I am being given a QgsVectorLayer (I wanted a list)"