Python Forum
Problem printing last element from a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem printing last element from a list
#1
Hi, I'm having a problem printing the last element from a list.
I'm scanning a file for lines that have words 'find-1', 'find-2', 'find-3' and so on.
I thought I will append all matching lines to a list and print only the last element from the list (last matched line).
For some reason script prints all lines from the list not just the last one.
here is a part of the code:
import io

logDir = 'C:/somedir/'
fout_w = open('C:/Dir/f.txt','w')

for fn in os.listdir(logDir):
    if os.path.isfile(os.path.join(logDir, fn)):               
        dir_f = logDir+fn                 
        mylst = []
        with io. open(dir_f, encoding='utf-8', errors='ignore') as f :          
            for line in f : 
                if 'find-1' in line:
                    mylst.append(line)                
                    fout_w.write(mylst[-1] + "   =================   "+dir_f+"\n") 
                    print (mylst[-1]) 
                    fout_w.write(mylst[-1]+'\n')

                elif 'find-2' in line:
                    mylst.append(line) 
                    fout_w.write(mylst[-1]+"  =================   "+dir_f+"\n") 
                    print (mylst[-1]) 
                    fout_w.write(mylst[-1]+'\n')  
fout_w.close()
Thank you!
Reply
#2
You appear to be printing within the same loop that you're adding the lines.

So when you add the first line, you then print out the last line (which is also the first).
Then the next time you add another line and print out the (newly) last line.
tester_V likes this post
Reply
#3
1  if 'find-1' in line:
2      mylst.append(line)                
3      fout_w.write(mylst[-1] + "   =================   "+dir_f+"\n") 
4      print (mylst[-1]) 
5      fout_w.write(mylst[-1]+'\n')
How is this supposed to only print the last of multiple matches? Each time you find a match you append it to the list, write it to a file (twice?) and print it to stdout. Granted you print the line using the last line in the list, but that doesn't stop you from writing the line each time the pattern is found.

You don't provide enough information to get good feedback on how to solve this problem so I am going to guess. My guess is you want your output file to look something like this:
Output:
find-1 blah blah ========== logfile1 find_1 blah blah find_1 blah blah find_1 blah blah find-2 blah blah ========== logfile3 find_2 blah blah find_2 blah blah find_2 blah blah
And in the console you should see
Output:
find_1 blah blah blah find_2 blah blah blah
If this is what you are looing for you will need to identify when you start finding a pattern and when you stop finding a pattern. There is no reason for a list. All you need to remember is what pattern matched the previous line and the current line (can be none).
import io
 
logDir = 'C:/somedir/'
fout_w = open('C:/Dir/f.txt','w')

def find_pattern(line, patterns):
    '''Find if any of the patterns are in line.  Return matching pattern'''
    for pattern in patterns:
        if pattern in line:
            return pattern
    return none

for fn in os.listdir(logDir):
    if os.path.isfile(os.path.join(logDir, fn)):               
        dir_f = logDir+fn                 
        with io. open(dir_f, encoding='utf-8', errors='ignore') as f :
            last_pattern = None  # Reset pattern at start of each file
            for line in f :
                # Scan line for matching patterns
                pattern = find_pattern(line, ('find-1', 'find-2'))

                # If we found a pattern write line to fout
                if pattern:
                    # Is this start of block containing new pattern?
                    if pattern != last_pattern:
                        # First time
                        print(line)
                        fout_w.write(f'{line}   =================   {dir_f}\n')
                    else:
                        # Repeats of same pattern
                        fout_w.write(f'{line}\n')
                last_pattern = pattern
fout_w.close()
tester_V likes this post
Reply
#4
I see your point! Thank you! I think I'm good now...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  element in list detection problem jacksfrustration 5 320 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  list in dicitonary element problem jacksfrustration 3 694 Oct-14-2023, 03:37 PM
Last Post: deanhystad
Question Inserting Numerical Value to the Element in Optionlist and Printing it into Entry drbilgehanbakirhan 1 802 Jan-30-2023, 05:16 AM
Last Post: deanhystad
  Find (each) element from a list in a file tester_V 3 1,205 Nov-15-2022, 08:40 PM
Last Post: tester_V
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,833 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,209 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  How to solve this simple problem? Check if cvs first element is the same in each row? thesquid 2 1,224 Jun-14-2022, 08:35 PM
Last Post: thesquid
  How to find the second lowest element in the list? Anonymous 3 1,998 May-31-2022, 01:58 PM
Last Post: Larz60+
  check if element is in a list in a dictionary value ambrozote 4 1,963 May-11-2022, 06:05 PM
Last Post: deanhystad
Question Printing through list.. again jesse68 2 1,141 Apr-16-2022, 03:24 PM
Last Post: jesse68

Forum Jump:

User Panel Messages

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