简体   繁体   中英

Reading comma separated values

My file has 5 values separated by 1 comma and 1 space. Which are: 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).

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'

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

You can instead do, using the ast library

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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