First problem is that the first line of your file has no data, but a header. You even try to handle this by replacing an empty string , but soon after you try to convert the value to integer. What integer value should be the string '\n'
? That's why it gives the error.
You can skip the first line by doing:
for i in conteudo[1:]:
...
Second problem is that when you read from a file you will always have a string . That is, b
and c
will be strings and when you do b+c
you will concatenate both and not add the integer values. To add, you need to convert to integer before:
print( int(b) + int(c) )
Getting something like this:
arq=open('pergunta.txt','r')
conteudo=arq.readlines()
arq.close()
for i in conteudo[1:]:
a=i.split(',')
b=a[1]
c=a[2]
print(int(b) + int(c))
But we have how to improve this code ...
import csv
with open('pergunta.txt') as stream:
reader = csv.DictReader(stream)
for row in reader:
print(int(row['n1']) + int(row['n2']))
The file opens within a context manager, so you do not have to worry about closing the file - and the file is traversed by a generator, which avoids having to save the entire contents of the file in memory as with readlines()
;
The file is read using the csv
package, with class DictReader
, which converts each line of the file into a dictionary using the first line as the name of the columns;
>
The sum of the values is done in the same way, but now accessing the n1
and n2
values of the dictionary;