Feb-20-2021, 10:10 AM
Without any assumption about the number of different animals in the file maybe something like this.
from datetime import datetime now = datetime.now() date_time = now.strftime("%m/%d/%Y") to_app ='C:/02/All_an.txt' animals = dict() with open (to_app, 'r+') as app: for ln_in_file in app : ln_in_file=ln_in_file.strip() line, P, num, animal = ln_in_file.split(',') if animal in animals: animals[animal]['count'] += int(num) else: animals[animal] = {'count': int(num), 'P': P, 'date': date_time} for animal in animals: print(f"{animals[animal]['date']},{animals[animal]['count']},{animals[animal]['P']},{animal}")As I don't know anything about the function of 'P' and 'lineNN', I omitted the 'lineNN' and replaced it with the date, but kept the rest. If this is not necessary, the code can be much simplified:
from datetime import datetime now = datetime.now() date_time = now.strftime("%m/%d/%Y") to_app ='C:/02/All_an.txt' animals = dict() with open (to_app, 'r+') as app: for ln_in_file in app : ln_in_file=ln_in_file.strip() line, P, num, animal = ln_in_file.split(',') if animal in animals: animals[animal] += int(num) else: animals[animal] = int(num) for animal, count in animals.items(): print(f"{date_time},{count},P,{animal}")