As Fiona works with dictionaries, it is easy.
With the example of Finding the common borders between polygons in the same shapefile
import fiona
from shapely.geometry import shape, mapping
# load the shapefile as an iterable
polys = fiona.open("polygons.shp")
Now, with the itertools module:
import itertools
for pol1,pol2 in itertools.combinations(polys, 2):
if shape(pol1['geometry']).touches(shape(pol2['geometry'])):
print "Polygon ",pol1['properties']['id'], " touches Polygon " , pol2['properties']['id']
Polygon 1 touches Polygon 4
Polygon 2 touches Polygon 4
Polygon 3 touches Polygon 4
And directly:
schema = {'geometry': 'LineString','properties': OrderedDict([(u'poly1', 'int:10'), (u'poly2', 'int:10')])}
with fiona.open('intersection2.shp','w','ESRI Shapefile', schema) as output:
with fiona.open("intersections.shp") as polys:
for pol1,pol2 in itertools.combinations(polys, 2):
geompol1 = shape(pol1['geometry'])
geompol2 = shape(pol2['geometry'])
if geompol1.touches(geompol2):
output.write({'geometry':mapping(geompol1.intersection(geompol2)), 'properties': {'poly1':pol1['properties']['id'],'poly2':pol2['properties']['id']}})
Control
for line in fiona.open("intersection2.shp"):
print line['properties']
OrderedDict([(u'poly1', 1), (u'poly2', 4)])
OrderedDict([(u'poly1', 2), (u'poly2', 4)])
OrderedDict([(u'poly1', 3), (u'poly2', 4)])