Feb-20-2021, 04:46 AM
Hi,
I need to 'sum' all elements by their kind.
All dogs, cats, and fishes.
I Cannot wrap around my mind around this small task.
Here is a kind of file as an example:
line01,P,2,dog
line02,P,1,dog
line33,P,7,dog
line03,P,3,cat
line04,P,5,cat
line11,P,8,fish
line12,P,3,dog
line16,P,2,dog
line04,P,2,cat
line11,P,12,fish
I need to print out a number of Dogs, Cats, and fishes and replace the first line with a time stamp.
19/02/2021,P,15 dog
19/02/2021,P,10,cat
19/02/2021,P,20,fish
I scanned the file and made a list of the animals --- 'list'.
And I thought I would use the list to filter 'animals' by its kind and 'sum' them, for some reason it does not work.
Code:
Thank you.
I need to 'sum' all elements by their kind.
All dogs, cats, and fishes.
I Cannot wrap around my mind around this small task.
Here is a kind of file as an example:
line01,P,2,dog
line02,P,1,dog
line33,P,7,dog
line03,P,3,cat
line04,P,5,cat
line11,P,8,fish
line12,P,3,dog
line16,P,2,dog
line04,P,2,cat
line11,P,12,fish
I need to print out a number of Dogs, Cats, and fishes and replace the first line with a time stamp.
19/02/2021,P,15 dog
19/02/2021,P,10,cat
19/02/2021,P,20,fish
I scanned the file and made a list of the animals --- 'list'.
And I thought I would use the list to filter 'animals' by its kind and 'sum' them, for some reason it does not work.
Code:
from datetime import datetime now = datetime.now() date_time = now.strftime("%m/%d/%Y") to_app ='C:/02/All_an.txt' list = ['dog','cat','fish'] with open (to_app, 'r+') as app : for ln_in_file in app : ln_in_file=ln_in_file.strip() for ech_element in list : Sum = 0 if ech_element in ln_in_file : spel =ln_in_file.split(",") spel[2]=int(spel[2]) print ("======================== ",spel[2]) Sum=(spel[2]+spel[2]) break print (Sum)I'm opening my file with 'r+' for some reason the file is not readable if I open it with 'append'
Thank you.