2

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

3
  • 6
    Please, don't use screenshots for error messages, copy the text and paste it into your questions and use code formatting. – user2856 Sep 5 '20 at 9:44
  • 2
    Welcome to Geographic Information Systems! Welcome to GIS SE! We're a little different from other sites; this isn't a discussion forum but a Q&A site. Your questions should as much as possible describe not just what you want to do, but precisely what you have tried and where you are stuck trying that. Please check out our short tour for more about how the site works. – Ian Turton Sep 5 '20 at 9:58
  • 4
    You have 3 format operators %s and 8 format arguments (",",",",",","x","y"). Your xField & yField should be "Longitude" and "Latitude" not "x" and "y" – user2856 Sep 5 '20 at 10:16
2

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)

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.