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?
2 Answers 2
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
What about this solution? reader = shapefile.Reader(r'/Users/name/Documents/shapefile.shp'). Just add r before the string chain. otherwise try by using the \ instead of /.
-
A raw string (
r'some string'
) will have no effect on forward slashes and changing forward slashes to backwards will not work on a non-Windows OS.user2856– user28562019年04月15日 02:42:35 +00:00Commented Apr 15, 2019 at 2:42
os.path.exists()
can find the file first.