I have some features selected by using "Select Features by Freehand" tool in QGIS and try to find the buffer for those selected features alone and write the city and state names within in the buffer to a csv file. My code and image is attached for a clear understanding. it is writing an csv file in the given location but nothing is found inside the csv.
And my code is
import csv
selection = layer.selectedFeatures()
layer = qgis.utils.iface.activeLayer()
columns=['name', 'state' ]
for feature in selection:
mbuf = feature.geometry().buffer(50, 2)
iterFeat = layer.getFeatures()
for f in iterFeat:
geom2 = f.geometry()
valTest = QgsGeometry.within(geom2, mbuf)
lsNearCities = []
if valTest:
idx = selection.fieldNameIndex('name')
idx1 = selection.fieldNameIndex('state')
nearCity = f.attributes()[idx]
state = f.attributes()[idx1]
state_and_cities = str(state) + "," + nearCity
lsNearCities.append(state_and_cities)
print lsNearCities