I am new to using PyCharm, but I am trying to
-
cut out 4 rows from a county shapefile
-
from that 4 rows specify the columns or attributes to also be extracted
-
and output the result as a new shapefile.
but when I try this code, it gave me some errors, please any ideas?
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
new error after rectifying file path
SyntaxError: positional argument follows keyword argument
import gdal_workaround
import fiona
import shapely
if __name__ == "__main__":
with fiona.open('C:\\Users\\Desktop\\GEM\\20test\\counties\\counties.shp') as input:
output_schema = input.schema.copy()
with fiona.open(C:\\Users\\Desktop\\GEM\20test\\counties\\counties2.shp , 'w', 'ESRI Shapefile',output_schema, crs=input.epsg, 4326) as output:
for elem in selection:
output.write({'properties': elem['nut2name'],'geometry': elem['polygon']})
Best Answer
What you are trying to do can indeed be done with Fiona and Shapely.
for this error:
The problem is in your
fiona.open
call here:You have
4326
in the function call after specifyingcrs=input.epsg
. Since you're specifying the CRS as the same as the input file, you don't need the4326
there. This isn't an error with fiona necessarily but something that's not allowed in Python:Alright, now to the meat of the issue. You want to "select" certain rows from your input shapefile. You can do that easily, you just need to look at the values of the columns you want to "select" using in each row of the shapefile. In
fiona
, the records are converted to GeoJSON structure, so you can access attributes in theproperties
member of the record. Imagine we have a shapefile of counties with three columns, the name, the fips, and the population, and we want to "select" the counties where population is greater than 100,000 people. We only want to write out the name and the population.