3

I have hit a snag using pyqgis in QGIS 3. I want to convert a set of CSVs (20 total) into point shapefiles but I am struggling with just the single CSV case. My code is based on this blogpost (https://www.geodose.com/2018/07/python-qgis-tutorial-adding-csv-data.html). I keep getting the same error but the "reason" section of the error message is always empty.

My code:

This is the full code, I have not imported any additional packages.

path = "C:/Users/.../Weather/CSVs/precip_1992.csv"
uri = path + "?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "longitude", "latitude","epsg:4326")
vlayer = QgsVectorLayer(uri,'Points', 'delimitedtext')
print(vlayer.isValid())

iface.addVectorLayer(uri,'Points','delimitedtext')

The error message in the "messages" log:

    2019-03-13T15:23:27     CRITICAL    Layer is not valid : The layer 
    C:/Users/.../CSVs/precip_1992.csv?encoding=UTF-8&delimiter=,&xField=longitude&yField=latitude&crs=epsg:4326 is not a valid
 layer and can not be added to the map. Reason:

The error message in the "delimited" log:

    2019-03-13T15:27:59     WARNING    
File cannot be opened or delimiter parameters are not valid

Sample of my csv file:

longitude,latitude,year,sum_precip,avg_precip
-179.75,71.25,1992,150.3,12.525001
-179.75,68.75,1992,189.5,15.791667
-179.75,68.25,1992,226.7,18.891666
-179.75,67.75,1992,287.10001,23.925001
2

You need to prefix the path with file:///, this is due to QGIS using the file URL scheme when locating files.

So replace:

path = "C:/Users/.../Weather/CSVs/precip_1992.csv"

with:

path = "file:///C:/Users/.../Weather/CSVs/precip_1992.csv"

Example


Your layer should now be valid (tested with QGIS 3.4).

  • 1
    Dear @Joseph, do you know why file:/// requires three slashes? – Taras Mar 14 at 11:39
  • 1
    @Taras - The provider string is based on the file URL scheme so in order to access locally stored files, the path needs to be prefixed with the mentioned syntax. – Joseph Mar 14 at 11:47

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.