如何绕过字符串在文本文件中执行添加 [英] How to perform addition in text file bypassing strings

查看:13
本文介绍了如何绕过字符串在文本文件中执行添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

        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:无法将字符串转换为浮点值:'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

推荐答案

修改你的代码如下:

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

这篇关于如何绕过字符串在文本文件中执行添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆