Python Forum

Full Version: Problem printing last element from a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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.
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()
I see your point! Thank you! I think I'm good now...