Home > Mobile >  How to read txt.file and find sum of different products with different prices
How to read txt.file and find sum of different products with different prices

Time:11-07

I have a following text-file products.txt:

Product;Amount;Price Apple;3;10.00 Banana;1;5.00 Lemon;2;3.00 Orange;4;20.00 Apple;4;8.00

I want read this file and make a new text-file newfile.txt, which contains value of each row (Amount X Price):

30.00 5.00 6.00 80.00 32.00

Finally, I want to find the total sum of newfile.txt (which is 30 5 6 80 32 = 153)

Note, the price of same product can vary and we are not interested total sum of each product.

I started with creating class.

class DATA:
    product= ""
    amount= 0
    price= 0

def read (name):

 list = []
    file= open(name, 'r', encoding="UTF-8")
    file.readline()
    while (True):
        row= file.readline()
        if(rivi == ''):
            break
        columns= row[:-1].split(';')
        info= DATA()
        info.amount= int(columns[1])
        info.price= int(columns[2])
        info.total = info.amount * info.price
        file.append(info)
    tiedosto.close()
    return list

CodePudding user response:

This should work:

def read(name):
    total = 0

    ori = open(name, 'r', encoding="UTF-8")
    row = ori.readline()

    dest = open("newfile.txt", 'w', encoding="UTF-8")

    row = ori.readline()
    while (row != ""):
        row = row[:-1].split(';')
        res = int(row[1])  * float(row[2])
        total  = res
        dest.write(str(res)   "\n")
        row = ori.readline()
    
    ori.close()
    dest.close()
    print(total)

read("products.txt")

CodePudding user response:

A possibility would be to use csv from the standard library.

import csv

# fix files' paths
path1 = # file to read
path2 = # file to write

# read data and perform computations
rows_tot = [] 
with open(path1, 'r', newline='', encoding="utf-8") as fd:
    reader = csv.DictReader(fd, delimiter=";")
    for row in reader:
        rows_tot.append(float(row['Amount']) * float(row['Price']))

# total sum
print("Total sum:", int(sum(rows_tot)))

# save to file the new data
with open(path2, 'w', newline='') as fd:
    fieldnames = ("AmountXPrice",)
    writer = csv.DictWriter(fd, fieldnames=fieldnames)

    writer.writeheader()
    for value in rows_tot:
        writer.writerow({fieldnames[0]: f"{value:.2f}"})

Remark: it is not clear from the question the type of the various data, in case just change int with float or the other way around.

  • Related