[GIS] ShapefileException when reading shapefile using PyShp

pyshppythonshapefile

I'm trying to read in a shapefile and keep getting a File Not Found error and this exception:

ShapefileException: Unable to open /Users/name/Documents/shapefile.shp

Here's what I've got:

import shapefile

# read the shapefile
reader = shapefile.Reader('/Users/name/Documents/shapefile.shp')

I've tried several variations of that and still get the error. The shapefile exists and it works. It's also in the same folder as the .dbf and .shx files. Any ideas?

Best Answer

I could also get the ShapefileException when:

  • the path to a shapefile is wrong
  • the shapefile's name was wrongly specified
  • there is no permission to access the shapefile

First of all, I suggest to double check the path to your shapefile:

  • correctness of slashes /, backslashes \, double backslashes // based on the OS

As was mentioned by @Vince test whether the shapefile exists using isfile and exists functions from the os.path module:

import shapefile
from os.path import isfile, exists

absolute_path_to_file = '/Users/name/Documents/shapefile.shp'

dbf = absolute_path_to_file.replace('.shp', '.dbf')

if isfile(absolute_path_to_file) and exists(dbf):
    shp = shapefile.Reader(absolute_path_to_file)
    print(shp)

Another suggestion is to test your shapefile with the pytest package using functions from the test_shapefile.py:

import pytest
import shapefile

absolute_path_to_file = '/Users/name/Documents/shapefile.shp'

with pytest.raises(shapefile.ShapefileException):
    with shapefile.Reader(absolute_path_to_file) as sf:
        pass