简体   繁体   English

读取逗号分隔的值

[英]Reading comma separated values

My file has 5 values separated by 1 comma and 1 space. 我的文件有5个值,以1个逗号和1个空格分隔。 Which are: 1, 2, 3, 5, 6 分别是: 1、2、3、5、6

However, no matter what I try (strip, split, etc) I just cant process the file and sum it to an accumulator (suma = 0). 但是,无论我尝试什么(剥离,分割等),我都无法处理文件并将其求和到累加器(suma = 0)。

When I try to convert the values to intergers I get the following error: ValueError: invalid literal for int() with base 10: '1,2,3,5,6' 当我尝试将值转换为整数时,出现以下错误: ValueError:以10为底的int()的无效文字:'1,2,3,5,6'

How exactly can I read them, convert them and then sum them? 我如何准确地阅读它们,将它们转换然后求和?

def main():

input_file = open('sumadatos.txt', 'r')
line = input_file.readline()
while line != '':
    value = int(line)
    suma += value 
print suma

main()

One approach would be 一种方法是

with open('sumadatos.txt', 'r') as f:
    print(sum(map(int, next(f).split(','))))

int can consume leading and trailing whitespace, so int(' 1 ') => 1 int可以消耗前导和尾随空格,因此int(' 1 ') => 1

You can instead do, using the ast library 您可以改用ast

>>> f = open("sumadatos.txt")
>>> sum(ast.literal_eval(f.readline()))
17

But if you want to do it conventionally you can do 但是,如果您想按常规方式做,则可以

>>> sum(int(i) for i in f.readline().split(','))
17

The numpy library has some great built in functions for parsing in delimited files into arrays. numpy库具有一些强大的内置函数,用于将定界文件解析为数组。

from numpy import genfromtxt
data = genfromtxt('sumadatos.txt', delimiter=',')
print data.sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM