add number and delete n in python

Asked

Viewed 133 times

0

I have the txt file:

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

I want to add up the numbers, I did it this way:

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 not using the int comes out like this:

85
56
09

When using the int in print the following error appears:

ValueError: invalid literal for int() with base 10: '\n'
  • makes int(b)+int(c) that should work

1 answer

3


First problem is that the first line of your file has no data but a header. You even try to handle it by replacing it with a string empty, but soon after you try to convert the value to integer. What integer value should be the string '\n'? So make the mistake.

You can ignore 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 to say, b and c evening strings and when you do b+c you will concatenate both and not sum the integer values. To add, you need to convert to integer first:

print( int(b) + int(c) )

Leaving 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 can 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']))
  1. The file opens within a context manager, so you don’t 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 the readlines();

  2. The file is read with the aid of the package csv, with class DictReader, which converts each row of the file into a dictionary using the first row as the column name;

  3. The sum of the values is done in the same way, but now accessing the values n1 and n2 dictionary;

  • @Matheusandrade Are you sure? He should exhibit one below the other, because the print adds line break by default, except when set the parameter end.

  • Thank you very much!

  • yes bro was because of the end='' after I asked that I saw kk but vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.