'How to sum numbers with string from a text file when meet conditions in Python

I'm doing an inventory system which require me to print distribution list of particular item. If the particular item has distribute to the same shop for more than 1 time, it need to sum the quantity together.

I'm not allowed to use dictionary and pandas. Only list can be use

item need to search with code

transactions text file:

S001,T01,T Shirt,4

S001,T01,T Shirt,7

S002,T02,Shoe,9

S003,T02,Shoe,11

First one is shop code, second one is item code,after that will be item name and distribute quantity

Here is my code

x=open("transactions.txt","r")
numbers = []
total = 0
searchInput=input("Enter item code to search: ")
for line in x:
      lines = line.strip()
      s = lines.split(",")
      numbers.append(s)
      if not searchInput.lower() in lines.lower():
            continue
      column = -1
      record = len(numbers)
      for v in range(record):
            if searchInput == s[1]:
                  column = v
      if ((numbers[column][0] == numbers[column][0]) and (numbers[column][1] == numbers[column][1])):
            num = int(numbers[column][-1])
            total += num
if column >=0:
      a=numbers[column][0]+","+numbers[column][1]+","+numbers[column][2]+","+str(total)
      print(a)

When i key in T01 for searchInput, it can print properly with the latest total. But when i key in T02, it sum up my total too even shop code is different. It should print the 2 line of T02 without sum it up.

when i key in T02 for searchInput, the output should look like this

S002,T02,Shoe,9

S003,T02,Shoe,11



Solution 1:[1]

I've tried to guess your specific use case so my examples can be a bit off. First, let me work through some of your code with some comments from my side:

numbers = []
total = 0
x = open("transactions.txt","r")

for line in x:

    print(line)

    lines = line.strip()
    s = lines.split(",")

    numbers.append(s)
    print(numbers)

    if not searchInput.lower() in lines.lower():
        # keep only the lines which have a match with the search input
        continue

    column = -1
    record = len(numbers)
    print(f'len(numbers): {len(numbers)}')

    for v in range(record):
        # 
        if searchInput == s[2]:
            # s is the current line, 2 denotes the 3rd entry e.g. the item
            # column will be overwritten by v as long as searchInput matches s[2] exactly
            # column will therefore be equal to len(numbers)-1
            column = v
            print(f'column: {column}')

    if ((numbers[column][0] == numbers[column][0]) and (numbers[column][1] == numbers[column][1])):
        # if one item equals itself, and another item equals itself, then:
        # num is the integer of last value in the column record
        num = int(numbers[column][-1])
        total += num

Please notice how the output is not clear. One of the key features in using Python is to keep your code legible - easy to read, so when someone else (or your future self) returns to this code, you can pick up where you left.

Based on what you told, I've tried to rephrase your code in the following way. Please pay extra attention to the naming of variables. Note that this example is a very basic example and if you work with input data, you might want to wrap some try-except statements and error handling in there. Of course, you could also decide to switch to other libraries such as csv as you already have a comma separated values or even pandas where you can do groupby, name the columns for easier reading and even add datetime columns so you can filter through dates. Anyway, I think what you were trying to achieve was the following:

searchInput = input("Enter item code to search: ").lower()

records = list()
transactions = open("transactions.txt","r")

for record in transactions:
    # cleaning the record by stripping leading and trailing spaces, lowering cases and splitting on the commas
    clean_record = record.strip().lower().split(',')

    if any([searchInput in x for x in clean_record]):
        # keep only the lines which have a match with the search input
        records.append(clean_record)

total = dict()
for record in records:
    # now that we have all the records we want
    # we will retrieve the relevant information
    # we want a the sum of the values, printed for each store
    if record[0] not in total.keys():
        total[record[0]] = int(record[-1])
    else:
        total[record[0]] += int(record[-1])

for shop, tot in total.items():
    print(f'Shop: {shop} - Total: {tot}')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomerikoo