Summing numeric values in text files with Python

Asked

Viewed 353 times

2

I am writing a small Python project that consists of an application that adds expenses, storing the name and value of expenses in a text file and printing on the command line, and at the end computing the sum of the expenses. The idea is that every time I open the app, I can add new amounts to the total amount spent before. For example, the total spending was 100, the program stores this value and when I open again, I can add an expense of 20 reais and the program shows 120. It is possible to perform this type of operation by working only with python and files?

Follow the code of the project

while True:
    while True:
        try:
            opc = int(input(f'''=================================================
              MENU PRINCIPAL
=================================================
[1] Visualizar lista de compras
[2] Atualizar gastos
[3] Sair 
=================================================

Sua opção: '''))
        except (ValueError, TypeError):
            print('Tipo de dado digitado inválido! Digite novamente')
        else:
            break           
    if opc == 1:
        with open("arquivo.txt") as n:
            nome = n.read()
            print('='*49)
            print(nome)
            print('='*49)            
    elif opc == 2:        
        with open("arquivo.txt",'a') as n: 
            while True:                   
                x = str(input(f'Tipo de gasto: '))
                t = x.strip().capitalize()
                if len(t) < 20:
                    b = 20 - len(t)
                    h = t + (' '*b)
                if x.isalpha() == False:
                    print(f'Digite novamente: ')
                else:
                    break                  
            while True:
                try:                    
                    y = float(input(f'Valor do gasto (R$): '))
                except (ValueError, TypeError):
                    print('Tipo de dado digitado inválido! Digite novamente')

                else:
                    valores.append(y)
                    break 

            z = str(y)                    
            n.write(h)
            n.write(f'\t\t R${z}')
            n.write('\n')
            print(f'''
Novo registro de {x} adicionado''')

            soma = 0
            for i in valores:
                soma += i
            print(f'''
Soma                R${soma}''')

    elif opc == 3:
        print(f'Obrigado, volte sempre! ')
        break
    else:
        print(f'Opção inválida! Tente novamente: ')```

1 answer

1

Yes, you can use open to open a file in read format, get the value, add it inside the program and then write the file again with the updated value. Example:

def atualizaGastos(valor):
    with open("data.txt") as file:
        gastos = float(file.read())
    with open("data.txt","w") as file:
        file.write(str(gastos+valor))

If the file has more information than a simple number (expenses), you should know the exact position of this number in the file or use the module re to get expenses in any part of the file. If you don’t know what they are Regular Expressions search first for this subject and then use the module re to get the desired values in the file.

Browser other questions tagged

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