I'm using pyshp to create new shapefiles with Python 3. My code runs without errors, but when I open the resulting file in ArcMap I get this error:
The following datasource you added is missing spatial reference information.
This is not surprising, since I never told my code that the coordinates in the shapefile are supposed to be in EPSG:3006. How do I set this property in pyshp?
Here's some short example code. I want to tell the writer shape
that the coordinates in start
and stop
are in EPSG:3006.
import shapefile
start = [6400137, 321751] # Coordinates in EPSG:3006
stop = [6400095, 319357] # Coordinates in EPSG:3006
with shapefile.Writer("my_shapefile") as shape:
shape.fileType = 3 # Polyline
shape.field("FOO", "C", size = 32)
shape.field("BAR", "C", size = 32)
shape.line([[start, stop]])
shape.record("foo", "bar")
-
2Unlike osgeo.ogr, Fiona or GeoPandas, Pyshp doesn't manage projection files (look at Create a .prj Projection File for a Shapefile)gene– gene2019年06月03日 15:04:15 +00:00Commented Jun 3, 2019 at 15:04
-
Thanks @gene! Your comment, and especially the last link, solved my problem. If you would post it as an answer I would be happy to upvote and accept.Anders– Anders2019年06月03日 21:47:09 +00:00Commented Jun 3, 2019 at 21:47
1 Answer 1
Information about the coordinate system is stored in a separate projection file, that should have the same name as the shapefile, but a .prj extention.
As gene points out in comments, the Pyshp library doesn't handle projection files. So you will have to write the file yourself. Here's an example of how to do that:
# create the PRJ file
prj = open("%s.prj" % filename, "w")
epsg = 'GEOGCS["WGS 84",'
epsg += 'DATUM["WGS_1984",'
epsg += 'SPHEROID["WGS 84",6378137,298.257223563]]'
epsg += ',PRIMEM["Greenwich",0],'
epsg += 'UNIT["degree",0.0174532925199433]]'
prj.write(epsg)
prj.close()
If you want to find the correct file content for your coordinate system, I recommend you simply create a shapefile with that coordinate system in e.g. ArcCatalog, and then just copy paste the content of the created projection file.