How to perform addition in text file bypassing strings

China☆狼群 提交于 2019-12-20 06:26:47

问题


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))


来源:https://stackoverflow.com/questions/54534737/how-to-perform-addition-in-text-file-bypassing-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!