add number and exclude \ n in python

0

I have the txt file:

NOME,n1,n2
JOAO,8,5
MARIA,5,6
PEDRO,0,9

I want to add the numbers, I did the following:

arq=open('pergunta.txt','r')
conteudo=arq.readlines()
arq.close()

for i in conteudo:
    a=i.split(',')
    b=a[1].replace('n1','')
    c=a[2].replace('n2','')
    print(int(b+c), end='')

In print when I do not use the int it goes like this:

85
56
09

When I use int in print the following error appears:

ValueError: invalid literal for int() with base 10: '\n'
    
asked by anonymous 25.10.2018 / 14:48

1 answer

3

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;

  • 25.10.2018 / 15:04