I am trying to convert a .csv file to .shp using pyqgis. With this publication ETA managed to generate the file with all its extensions and the table of attributes but I do not see the entities (type point). column 1 and 2 have the information of Lat and Long the code I have is this:
ruta = "C:/Users/Pc/Desktop/MANUELITA/productividad/CSV/35300030000_C58_b.csv" # set the filepath for the input CSV
inp_tab = QgsVectorLayer(ruta, 'Input_Table', 'ogr')
salida = 'C:/Users/Pc/Desktop/MANUELITA/productividad/CSV/prueba.shp'
fields = inp_tab.fields()
crs = 4326
outLayer=QgsVectorFileWriter.writeAsVectorFormat(inp_tab, salida,"fields" ,inp_tab.crs() ,"ESRI Shapefile", layerOptions=['SHPT=POINT'])
the .csv fields looks like this: enter image description here
-
With your approach, you also need to set the geometry of each point to a feature. However, in my Editing Note there is another approximation by using an uri (uniform resource identifier) with delimiters.xunilk– xunilk2020年03月05日 01:24:17 +00:00Commented Mar 5, 2020 at 1:24
1 Answer 1
In this case, you also need to set the geometry of each point to a feature; as in following script:
ruta = '/home/zeito/pyqgis_data/temp_max.csv' # set the filepath for the input CSV
lon_field = 'x' # set the name for the field containing the longitude
lat_field = 'y' # set the name for the field containing the latitude
crs = 4326 # set the crs as needed
salida = '/home/zeito/pyqgis_data/temp_max.shp' # set the filepath for the output shapefile
spatRef = QgsCoordinateReferenceSystem(crs, QgsCoordinateReferenceSystem.EpsgCrsId)
inp_tab = QgsVectorLayer(ruta, 'Input_Table', 'ogr')
fields = inp_tab.fields()
outLayer = QgsVectorFileWriter(salida,
None,
fields,
QgsWkbTypes.Point,
spatRef,
"ESRI Shapefile")
pt = QgsPointXY()
outFeature = QgsFeature()
for feat in inp_tab.getFeatures():
attrs = feat.attributes()
pt.setX(float(feat[lon_field]))
pt.setY(float(feat[lat_field]))
outFeature.setAttributes(attrs)
outFeature.setGeometry(QgsGeometry.fromPointXY(pt))
outLayer.addFeature(outFeature)
del outLayer
I used a CVS file with many fields as in your case. After running above script in Python Console of QGIS 3.12, I got result of following image:
Editing Note:
Based in QGIS documentation, I also found the following solution:
uri = "file:///home/zeito/pyqgis_data/temp_max.csv?delimiter={}&xField={}&yField={}".format(",", "x", "y")
inp_tab = QgsVectorLayer(uri,
"temp_max",
"delimitedtext")
QgsProject.instance().addMapLayer(inp_tab)
salida = '/home/zeito/pyqgis_data/temp_max4.shp' # set the filepath for the output shapefile
crs = 4326 # set the crs as needed
spatRef = QgsCoordinateReferenceSystem(crs, QgsCoordinateReferenceSystem.EpsgCrsId)
outLayer=QgsVectorFileWriter.writeAsVectorFormat(inp_tab,
salida,
'UTF-8',
spatRef,
"ESRI Shapefile")
After running above script, result is totally equivalent to above image.