Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 exist, 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")

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 datapoints 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?

share|improve this question
How are you writing features to the new shapefile? – gsherman Mar 26 '13 at 14:37

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

import os

if os.path.isfile('c:/temp/toke2.shp'):
share|improve this answer
Nice, that works. Thank you. Now I just need to figure out who the addMapLayer is not working. – Toke Mar 27 '13 at 0:09
@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. – user25976 May 7 '14 at 0:33

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.