如何在文本文件中绕过字符串执行加法

时间:2019-02-05 12:44:13

标签: python-3.x csv math sum addition

我将csv文件转换为文本文件,并且想在文本文件中添加数字。当我运行代码时,出现错误。假设错误代码是我想要编写的逻辑,该逻辑将绕过我的字符串而只添加数字值。

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

输出(错误):data.extend(rowdata) ValueError: could not convert string to float Value: 'ANNUAL'

这是我的文本文件的内容:

ANNUAL BUDGET Q2 Q4

100 450 20

600 765 50

500 380 79

800 480 455

1100 65 4320

1 个答案:

答案 0 :(得分:1)

按如下所述修改您的代码:

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