If I want to read in a shapefile I do :
fn_shp = 'c:/xyz/fname.shp'
shp_layer = QgsVectorLayer(fn_shp, 'shp layer', 'ogr')
Does this interface (QgsVectorLayer) also accept a .csv file as an input? I am trying to read a .csv this way:
fn_csv = 'c:/xyz/fname.csv'
csv_layer = QgsVectorLayer(fn_csv, 'csv Layer', 'delimitedtext')
but it says that the layer is not loaded!
if not csv_layer.isValid():
print('Layer is not loaded')
I know that there is a possibility of reading a .csv file by importing CSV library, but I rather open my file as an object returned by "QgsVectorLayer" that is equipped with methods that allow me to access fields and features of this file relatively easily.
Another approach will be to convert the .csv file into a .shp file. But I don't know how to do this programmatically using PyQGIS.
-
What is the geometry type of your csv, if any?Bera– Bera2025年02月24日 13:37:07 +00:00Commented Feb 24 at 13:37
-
Hi @Bera, Each feature is a point. two fields (X/Y) represent the position of these points.Sina NAKHOSTIN– Sina NAKHOSTIN2025年02月24日 13:53:35 +00:00Commented Feb 24 at 13:53
-
One observation is that according to PyQgis cheet sheet one can use 'ogr' as the vector provider which supports many vector file formats. This way using .asValid() on the imported layer does not return False. I just do not know why 'delimitedtext' does not work!Sina NAKHOSTIN– Sina NAKHOSTIN2025年02月24日 13:57:13 +00:00Commented Feb 24 at 13:57
-
Does this help gis.stackexchange.com/questions/166517/…?user30184– user301842025年02月24日 14:40:16 +00:00Commented Feb 24 at 14:40
1 Answer 1
The answer to my question is given in QGIS cheet sheet. It is very important to correctly format the "url" for reading a .csv file. I copy the example in the document here:
uri = "file://{}/testdata/delimited_xy.csv?delimiter={}&xField={}&yField={}".format(os.getcwd(), ";", "x", "y")
vlayer = QgsVectorLayer(uri, "layer name you like", "delimitedtext")
QgsProject.instance().addMapLayer(vlayer)
in this example the file name is "/testdata/delimited_xy.csv" and it is assumed that the information of the geometries coordinates (here points) are provided in "x" and "y" fields of the .csv file.
The only issue might be that due to the lack of explicit information the imported layer lacks CRS info. this should be taken care of individually.