5

I'm trying to create an empty copy of a certain layer, so no objects only tablestructure, crs etc.

from qgis.utils import *
layer = qgis.utils.iface.activeLayer()
print layer.name()                           
provider = layer.dataProvider()
print provider.fields()[0].name()
writer1 = QgsVectorFileWriter("d:/temp/qgis/test3.shp", 
                              "CP1250", 
                              provider.fields(), 
                              provider.geometryType(), 
                              provider.crs(), 
                              "ESRI Shapefile")

When I open the created file (test3) there is no tablestructure, crs. etc.

Running the script the second time with test3 still open, it works.

Obviously I miss something .

enter image description here


An other good working solution I found later: http://gis.stackexchange.com/q/156096/67332/

it loads it into a memory layer.

JAS
  • 475
  • 3
  • 11
  • I don't understand your "it works" because your code doesn't work in that way for me. May you put an image of this behavior? – xunilk Jul 12 '17 at 15:16
  • @PolyGeo No its not a duplicate question. The other question is about memory layers. This one is not. I gave that link to the other question to let others users know that I found also another solution with another technique. – JAS Jul 13 '17 at 11:57

1 Answers1

4

I've tested in the QGIS Console with QGis 2.14.15 and run into the same issue.

The fix is simple, you just missed one step. You need to reset the Variable writer1.

I did it with writer1 = None which created the file as expected

LaughU
  • 4,176
  • 5
  • 21
  • 41
  • It only copy field names but not table structure (records). – xunilk Jul 12 '17 at 14:51
  • @xunilk jeah but thats what op is after or did I miss something? – LaughU Jul 12 '17 at 14:52
  • Thanks, that did the trick. working fine now. Putting writer1 = None at the end. – JAS Jul 12 '17 at 15:18
  • @JAS the best way for saying thanks here is accepting the answer that you reputed as the most useful for solving your issue. – mgri Jul 12 '17 at 15:22
  • @xunilk Sorry about the misunderstanding about tablestructure, I meant the fieldnames and their types. – JAS Jul 12 '17 at 15:24
  • Another good working resolution I found later: http://gis.stackexchange.com/q/156096/67332/

    it loads it into a memory layer.

    – JAS Jul 13 '17 at 08:09