Oct-30-2020, 02:58 AM
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:
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!