[Qgis-developer] vector writer : how to append new data to existing shapefile ?

Michaël Douchin michael.douchin at laposte.net
Thu Dec 13 03:08:13 EST 2007


Hi,

Just to tell what Martin adviced works well.
Careful : the
provider.addFeatures( [feature] )
doesn't work with only one feature, but needs a list of features.

Below is a bit of my code to
* create a new shape file if it doesn't exists and add the features
* open an existing shapefile to add some features to it

************
       if not os.path.exists( "myshape.shp") ): # si le shapefile 
n'existe pas
          #we create the new shapefile
          writer = QgsVectorFileWriter("myshape.shp"), "CP1250", fields, 
QGis.WKBPoint, None)
          existe=0
          if writer.hasError() != QgsVectorFileWriter.NoError:
            print "Error when creating shapefile: ", writer.hasError()
         
        else: #when the shapefile exists
          #on ouvre le fichier shape existant
          mylayer = QgsVectorLayer("myshape.shp"), "ma_couche", "ogr")
          myprovider = mylayer.getDataProvider()
          existe=1
        list_fet=[]
        for i in range(0,len(donnees)): #donnees is the list[[]] 
containing the data from the csv file
              fet = QgsFeature()
              fet.setGeometry(QgsGeometry.fromPoint( 
xform.transform(QgsPoint(longitude, latitude)) )  )
              fet.addAttribute(0, QVariant(local_date) ) #date
              fet.addAttribute(1, QVariant(local_heure) ) #heure locale
             # .......

              if existe == 0:
                writer.addFeature(fet)  # directly add each feature 
inside the loop
              if existe == 1:
                list_fet.append(fet)  # we add the feature in the list 
of feature "list_fet"

        if existe == 1:
          myprovider.addFeatures(list_fet)       #here we add all the 
features from list_fet to the shapefile

*************

Michael

Martin Dobias a écrit :
> On Dec 12, 2007 5:43 PM, Michaël Douchin <michael.douchin at laposte.net> wrote:
>   
>>  In an short way "Is it possible to open a shapefile in write mode and then
>> append some new data at the end" ?
>>     
>
> Yes, that's possible too :-)
>
> You can open your shapefile as a vector layer and then use its
> provider to add some features:
> layer = QgsVectorLayer(...)
> provider = layer.getDataProvider()
> provider.addFeatures( [ feature ] )
>
> And that's it. I didn't try it now but should work as expected.
> addFeatures() expects list of features, but of course you can add them
> one by one.
>
> Martin
>
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/qgis-developer/attachments/20071213/b0491711/attachment.html


More information about the Qgis-developer mailing list