TransWikia.com

Loading multiple CSVs into QGIS 3

Geographic Information Systems Asked by Ajie on June 22, 2021

I’ve been searching for the fastest way to load multiple CSV Files into QGIS 3.10.

My CSV-files consist of 5 columns:

Brand Name | Branch Name | Address | Latitude | Longitude

I am using Mac, and "files:///" might not work. Any suggestions?

I saw code related to this, and followed this. Here’s what I came up with:

import glob, os

csv_files="Users/ajie/Documents/RestoBrand_Py/SAMPLE CSVs/"
os.chdir(csv_files)

for fname in glob.glob("*csv"):
   uri = "files:///" + csv_files + fname + "?delimiter=%s&crs=epsg:4326&xField=%s&yField=%s" % (",",",",",","x","y")
   name = fname.replace('csv', '')
   lyr = QgsVectorLayer(uri, name, 'delimitedtext')
   QgsProject.instance().addMapLayer(lyr)

Here’s the error

enter image description here

One Answer

As mentioned in the comments by @user2856, there are too many arguments in the format call. To make the process more transparent, you can hard-code all the parameters. This should work (though not tested on Mac):

import os

directory = "Users/ajie/Documents/RestoBrand_Py/SAMPLE CSVs/"
 
def load_and_configure(path):
    path = os.path.join(directory, filename)
    uri = 'file:///' + path + "?type=csv&escape=&useHeader=yes&detectTypes=yes"
    uri = uri + "&crs=EPSG:4326&xField=Longitude&yField=Latitude"
    vlayer = QgsVectorLayer(uri, filename, "delimitedtext")
    QgsProject.instance().addMapLayer(vlayer)
 
for filename in os.listdir(directory):
    if filename.endswith(".csv"):
        load_and_configure(filename)

Answered by underdark on June 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP