By Dante


2019-03-13 22:43:07 8 Comments

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

1 comments

@Joseph 2019-03-14 11:05:14

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).

@Taras 2019-03-14 11:39:54

Dear @Joseph, do you know why file:/// requires three slashes?

@Joseph 2019-03-14 11:47:19

@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.

Related Questions

Sponsored Content

2 Answered Questions

[SOLVED] How to use SAGA Raster processing in processing scripts (QGIS3)

2 Answered Questions

1 Answered Questions

[SOLVED] QGIS heatmap issue

4 Answered Questions

[SOLVED] PostGIS importing shapefile error w/ official manager

  • 2014-08-08 14:27:43
  • diogoguidotte
  • 1931 View
  • 2 Score
  • 4 Answer
  • Tags:   postgis shapefile

1 Answered Questions

2 Answered Questions

1 Answered Questions

[SOLVED] QGIS Reprojecting csv point file to projected CRS

0 Answered Questions

Converting KML coordinates to Leaflet

1 Answered Questions

[SOLVED] Unable to add features in QGIS 2.4.0

  • 2014-10-15 16:28:52
  • Paul Ransom
  • 131 View
  • 1 Score
  • 1 Answer
  • Tags:   qgis shapefile proj

2 Answered Questions

[SOLVED] How to convert Point coordinates into CSV format?

Sponsored Content