Skip to main content
2 of 4
added 4 characters in body
Bera
  • 77.9k
  • 14
  • 78
  • 188

Unable to loop/delete with QgsVectorLayer and dataProvider

I have a csv file with the following columns:

table   geometry    field   type    typeName    len   precision

and my goal is to create a number of shp files programatically with PyQGIS.

Here's my code. Thanks in advance guys!

import sys
import re 
import csv
from PyQt4.QtCore import *
from PyQt4.QtGui import * 

reload(sys)  
sys.setdefaultencoding('utf8')
final_list = []

with open(r"D:\Users\Ravi_narayanan\Documents\shpgen.csv", "rU") as s:  
    reader_tables = csv.DictReader(s,delimiter=';')
    liste_tables = list(reader_tables)
    l_tables = [i['table'] for i in liste_tables]
    l_tables = set(l_tables)
    for table in l_tables:
        l1 = [line for line in liste_tables if line['table'] == table] 
        geometry = l1[1]['geometry']
        layer_mem = QgsVectorLayer(geometry+"?crs=epsg:2154",table,"memory")
        QgsVectorFileWriter.writeAsVectorFormat(layer_mem,r"D:\setupCAPFT2.00\{}.shp".format(table),"utf-8",None,"ESRI Shapefile",False)
        layer_path = "D:\{}.shp".format(table)
        shp = QgsVectorLayer(layer_path,table,'ogr')
        pr = shp.dataProvider()
        shp.startEditing()
        for field in l1:
            if field['type'] != 'Double':
                pr.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']))])
            else:
                pr.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']),int(field['precision']))])
        shp.updateFields()
        shp.commitChanges()
        shp.stopEditing()
        del layer_mem,shp,pr