0

I am trying to add a new column(field) in a CSV file and also populate the CSV file with the result of the multiplication between the 4th column(field) and 0.3048. my code copies everything in the CSV but failed to perform the operation in the line==>: ### append new column with feature attributes.

My plugin code:

filename = self.dlg.lineEdit.text()
with open(filename, ‘w’) as output_file:
selectedLayerIndex = self.dlg.comboBox.currentIndex()
selectedLayer = layers[selectedLayerIndex].layer()
fieldnames = [field.name() for field in selectedLayer.fields()]
# write header
line = ‘,’.join(name for name in fieldnames) + ‘\n’
output_file.write(line)
## wirte feature attributes
for f in selectedLayer.getFeatures():
line = ‘,’.join(str(f[name]) for name in fieldnames) + ‘\n’
output_file.write(line)
### append new column with feature attributes
open(filename, ‘w’) as output_file:
writer = csv.writer(output_file, lineterminator=’\n’)
reader = csv.reader(input_file)

all = []
row = next(reader)
row.append(‘Tile(Elev)’)
all.append(row)

for row in reader:
row.append(row[3]*0.3048)
all.append(row)

writer.writerows(all)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.