zeerock
zeerock

Reputation: 93

Print requested data from .txt file

I have a txt file with the following data:

buy apples 20
buy oranges 15
sold bananas 5
sold bananas 5
sold pears 8

I wrote a program to print out the total number of bananas sold, however I keep getting the error

cannot unpack non-iterable builtin_function_or_method object

How do I fix this issue?

with open("update.txt") as openfile:
        for line in openfile:
            action, fruit, quantity = line.split
            if action == 'sold':
                    print(f"{fruit} {quantity}")

The output should be:

bananas 10
pear    8

Upvotes: 1

Views: 62

Answers (1)

buddemat
buddemat

Reputation: 5301

For one, your need to call split as a function, i.e. with parentheses:

action, fruit, quantity = line.split()

Additionally, if you want to sum up the values for each fruit, you obviously cannot just print them as you read them. One way is e.g. to store each sold fruit in a dict and sum up the quantities. Then print them at the very end:

# initialize empty dictionary
sold_fruit = {}

with open("update.txt") as openfile:
    for line in openfile:
        action, fruit, quantity = line.split()
        if action == 'sold':
            # set value for key '<fruit>' to the sum of the old value (or zero if there is no value yet) plus the current quantity
            sold_fruit[fruit] = sold_fruit.get(fruit,0) + int(quantity)

for frt, qty in sold_fruit.items():
    print(f"{frt} {qty}")

Output:

bananas 10
pears 8

Upvotes: 2

Related Questions