Python Forum
splitting lines, need to add element of same kind
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
splitting lines, need to add element of same kind
#1
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:
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.
Reply


Messages In This Thread
splitting lines, need to add element of same kind - by tester_V - Feb-20-2021, 04:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  What kind of list is this? jesse68 2 1,131 Jun-29-2022, 05:02 PM
Last Post: rob101
  What kind of object is this? Moris526 5 2,511 Dec-27-2020, 06:41 AM
Last Post: Gribouillis
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 5,825 Aug-10-2020, 11:01 PM
Last Post: medatib531
  How to do this kind of IF STATEMENT? glennford49 4 2,637 Jun-17-2020, 09:45 AM
Last Post: glennford49
  Splitting lines ang grouping three at once samsonite 5 2,752 Jun-21-2019, 05:19 PM
Last Post: ichabod801
  Unable to locate element no such element gahhon 6 4,466 Feb-18-2019, 02:09 PM
Last Post: gahhon
  How to write a code to get this kind of output in IDLE kavindu 5 3,545 Oct-28-2018, 07:46 PM
Last Post: wavic
  Newbie question for a kind of rolling average of list of lits zydjohn 3 3,322 Dec-16-2017, 11:41 PM
Last Post: ezdev
  Change single element in 2D list changes every 1D element AceScottie 9 12,066 Nov-13-2017, 07:05 PM
Last Post: Larz60+
  Compiler fault or some kind of weird referencing bug? Joseph_f2 11 9,145 May-09-2017, 08:50 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020