Noob Saibot
Noob Saibot

Reputation: 113

Summing up the price from file and then printing and appending the total value

I have created a store program that saves the product name and price as the user select the product and then append into the file. Now i am trying to create a shopping cart like thing from that file. The difficulty i am getting is that how can i sum up all the prices from that file.

my file contains:

You have purchased 5 banana of Rs. 500
You have purchased 2 banana of Rs. 200
You have purchased 1 banana of Rs. 100

Rs. is my currency where as [500,200,100] is price. How can i read it from file and then sum up and print.

I've tried using split function

split(Rs.)

by using this function:

    for line in f.readlines():
    uselessdata,price = line.split("Rs.")
    lst.append([uselessdata, int(price)])

but it gives error: ValueError: not enough values to unpack (expected 2, got 1)

Upvotes: 0

Views: 32

Answers (1)

abarnert
abarnert

Reputation: 365945

Your actual sample input doesn't produce this error.

But it's pretty easy to generate a file that does: For example, just stick a blank line on the end of the file. If that's what your real data looks like, this is what will happen:

>>> line = '\n'
>>> uselessdata,price = line.split("Rs.")
ValueError: not enough values to unpack (expected 2, got 1)

The reason should be obvious, but in case it isn't:

>>> line.split("Rs.")
['\n']

So, you need to decide how to handle such cases. One possibility is to just skip all errors—or maybe log them:

for line in f.readlines():
    try:
        uselessdata,price = line.split("Rs.")
        lst.append([uselessdata, int(price)])
    except ValueError as e:
        logging.info(f'{line} failed to split or parse')

Another is to handle just the particular case you expect:

for line in f.readlines():
    if line.strip():
        uselessdata,price = line.split("Rs.")
        lst.append([uselessdata, int(price)])

Another is to edit your file to remove the incorrect line.

But you can't choose between these until you actually look at the file and see what errors you have—or run in the debugger, or add some print statements, so you can see the specific line that's failing—and decide what you want to do about them.

Upvotes: 1

Related Questions