6

I am creating a shapefile in Python by:

driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.CreateDataSource('c:/temp/toke2.shp')
layer = datasource.CreateLayer('layerName',geom_type=ogr.wkbLineString)

If the file toke2.shp doesn't exist, it will be created. If it exists, I can't run this code and overwrite the old file. I need an overwrite function or a delete function. I run QGIS in admin mode.

My other problem is when I want to add the shapefile to QGIS by:

vlayer = QgsVectorLayer("c:/temp/toke2.shp", "toke2", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

If I add the file in QGIS by "Layer> add vector layer", it works fine. When I use the code in the python console in QGIS it also works fine. But if I use this code in my plugin the file is added to QGIS, but it is empty. So for some reason it doesn't add the data points in the file, it is just adding an empty shapefile.

In my plugin I import this:

 from osgeo import ogr
 from osgeo import osr
 import math
 from PyQt4.QtCore import *
 from PyQt4.QtGui import *
 from qgis.core import *
 import qgis.utils
 import resources_rc

Does anyone have a solution to these problems?

nmtoken
13.6k5 gold badges39 silver badges91 bronze badges
asked Mar 26, 2013 at 3:05
1
  • How are you writing features to the new shapefile? Commented Mar 26, 2013 at 14:37

2 Answers 2

6

You can check for existence of a file and remove it using:

import os
if os.path.isfile('c:/temp/toke2.shp'):
 os.remove('c:/temp/toke2.shp')
Pablo
9,8856 gold badges45 silver badges73 bronze badges
answered Mar 26, 2013 at 14:37
2
  • Nice, that works. Thank you. Now I just need to figure out who the addMapLayer is not working. Commented Mar 27, 2013 at 0:09
  • 1
    @gsherman is there an efficient way to remove all affiliated layers of the shapefile in one go (not individually)? I find that I'm still left with dbf prj qpj and shx using these lines of code. Commented May 7, 2014 at 0:33
1

I made it work by using memory to create a layer instead of making a shp file.

answered Apr 3, 2013 at 2:19

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.