Prepare csv file from vector data using python in QGIS
Here is code :
from qgis.core import QgsVectorLayer, QgsProject
shapefile_path = 'D:/your_folder_path/bangladesh_administrationlevel2.shp'
layer = QgsVectorLayer(shapefile_path,'shapefile_layer','ogr')
if not layer.isValid():
print('Layer is not load')
QgsProject.instance().addMapLayer(layer)
csv_path = 'D:/your_folder_path/output.csv'
with open(csv_path,'w') as csv_file:
field_names = [field.name() for field in layer.fields()]
print(field_names)
csv_file.write(','.join(field_names)+'\n')
for feature in layer.getFeatures():
attribute_values = [str(feature[field.name()]) for field in layer.fields()]
csv_file.write(','.join(attribute_values)+ '\n')