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.Any help would be appreciated. ![enter image description here][1] [1]: https://i.sstatic.net/KXWCQ.png And my code is import csv layer = qgis.utils.iface.activeLayer() features = layer.selectedFeatures() mbuf = feature.geometry().buffer(50, 2) iterFeat = layer.getFeatures() for f in iterFeat: geom2 = f.geometry() valTest = QgsGeometry.within(geom2, mbuf) if valTest: idx = layer.fieldNameIndex('name') idx1 = layer.fieldNameIndex('state') nearCity = f.attributes()[idx] state = f.attributes()[idx1] state_and_cities = str(state) + "," + nearCity lsNearCities.append(state_and_cities) filteredFields = [] for feature in features: attrs = lsNearCities with open('E:/Kcube/test2.csv', 'w') as csvfile: writer = csv.writer(csvfile, delimiter=',') for field in filteredFields: writer.writerow(field)