I converted my csv file to text file and I want to add the numbers inside the text file. When I run my code get an error. Assuming the error code I want to write logic that would bypass my strings and just add the numeric values.
`import csv
csv_file = 'Annual Budget.csv'
txt_file = 'annual_budget.txt'
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
reader = csv.reader(my_input_file)
for row in reader:
my_output_file.write(" ".join(row)+'\n')
data = []
with open(r'annual_budget.txt') as f:
for line in f:
fields = line.split()
rowdata = map(float, fields)
data.extend(rowdata)
print(sum(data)/len(data)
Output (Error): data.extend(rowdata)
ValueError: could not convert string to float Value: 'ANNUAL'
Here are the contents of my text file :
ANNUAL BUDGET Q2 Q4
100 450 20
600 765 50
500 380 79
800 480 455
1100 65 4320
Modified your code as mentioned below: