0

I have been searching on GIS for a solution to this essentially I have a shapefile .shp on my desktop also where I am saving this py script. The .shp also has the associated files. But when I try this code snippet I found on here I get back "couldn't load shapefile":

import osgeo
import osgeo.ogr
try:
    shapefile = osgeo.ogr.Open("world.shp")

    if shapefile: # checks to see if shapefile was successfully defined
        numLayers = shapefile.GetLayerCount()
    else: # if it's not successfully defined
        print "Couldn't load shapefile"
except: # Seems redundant, but if an exception is raised in the Open() call,
    # you get a message
    print "Exception raised during shapefile loading"

    # if you want to see the full stacktrace - like you are currently getting,
    # then you can add the following:
    raise

Any ideas on why this would not work? I am using spyder and have gdal installed onto anaconda.

  • Have you try to load the .shp in a gis software like qgis? Maybe is corrupted – Oscar Campo Apr 26 '18 at 17:11
2

It works fine. I ran it without errors.

You could modify it a bit so it is obvious if it works:

if shapefile: # checks to see if shapefile was successfully defined
    numLayers = shapefile.GetLayerCount()
    print(numLayers)

Make sure you are running it in the same folder as world.shp.

  • Thanks but it seems that it still gives me "cannot open shapefile". I have that file that says world.shp on my desktop. I don't know why it won't open. I opened world.shp on QGIS and it came up just fine. Am not sure but maybe it has to do with where python is being executed/saved and where this world.sph file is (desktop). Although the py script is also saved on my desktop. Also this is being used through Spyder python 2.7. – Hue_ Apr 26 '18 at 20:09
  • Where does my shape file have to be in order for it to open? – Hue_ Apr 26 '18 at 20:43
  • It doesn't matter where your file is if you specify the full path to it. Usually though, next to your .py file should work. – GHRF Apr 27 '18 at 8:45
  • Yeah if you don't specify a full path it needs to be where you run the script from. – HeikkiVesanto Apr 27 '18 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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