How to perform addition in text file bypassing str

2020-05-06 09:26发布

问题:

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

回答1:

Modified your code as mentioned below:

  with open(r'annual_budget.txt', 'r') as f:
     reader = csv.reader(f)
     headers = reader.next() # this will yield first row i.e columns if python 3: Use next(reader) instead of reader.next()
     for line in reader:
         rowdata = map(float, line)
         data.extend(rowdata)
     print(sum(data)/len(data))