![]() |
If match not found print last line - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: If match not found print last line (/thread-33431.html) |
If match not found print last line - tester_V - Apr-25-2021 Greetings! I need to print the last line of a file if a match (second match) not found. I'm printing all the lines with "match-2" for each "match-1" line. line-1 match-1 line something else line something else line-4 match-2 line-5 match-2 line-6 match-2 line something else line something else line something else line something else line-11 match-1 line something else line something else line-14 match-2 line something else line something else line-17 last match-1 line-18 last need to print Here is the code I got so far: with open('C:/02/file2.txt','r') as mf : for el in mf : el=el.strip() if 'match-1' in el : one=el.strip() #print ("one "+one) elif 'match-2' in el : tr = el print(one+" , "+tr)Code prints : line-1 match-1 , line-4 match-2 line-1 match-1 , line-5 match-2 line-1 match-1 , line-6 match-2 line-11 match-1 , line-14 match-2 Need also to print : line-17 last match-1 , line-18 last need to print Thank you! RE: If match not found print last line - menator01 - Apr-25-2021 Maybe not the best way but might help #! /usr/bin/env python3 matches = [] with open('file.txt') as file: lines = file.readlines() for line in lines: if 'match-1' in line or 'match-2' in line: matches.append(line) print(line.strip()) if len(matches) % 2 != 0: print(lines[-1])
RE: If match not found print last line - tester_V - Apr-26-2021 I like your thought! It is great but I need to go with a line-by-line checking the file, it is not a small file and no tone file. Thank you! |