0

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.

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Feb 24 at 12:25
4
  • What is the geometry type of your csv, if any? Commented Feb 24 at 13:37
  • Hi @Bera, Each feature is a point. two fields (X/Y) represent the position of these points. Commented 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! Commented Feb 24 at 13:57
  • Does this help gis.stackexchange.com/questions/166517/…? Commented Feb 24 at 14:40

1 Answer 1

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.

answered Feb 24 at 15:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.