Python Forum

Full Version: Print the line before the corrent line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
I'm searching lines for two words "PASSED" and "FAILED"
I need to get the line before "PASSED" and the "FAILED" line.
I'm definitely doing it wrong,
the script I wrote does not get me the line I'm looking for, it actually prints the same line.
ftor = open('C:/01/prt.csv','r') for num, el in enumerate(ftor, 1): el=el.strip() if 'PASSED' in el : to_gt =num-1 print(f" BEFORE PASSED ->{to_gt} - {el}") pas_fail = el.split(",") print (f" {num} {pas_fail[9]} - {el}") print("") elif 'FAILED' in el : to_gt =num-1 print(f" BEFORE FAILED ->{to_gt} - {el}") pas_fail = el.split(",") print (f" {num} {pas_fail[9]} - {el}") print("") ftor.close()

Thank you!
I don't understand your code, but if you just need to remember the last line for some reason:
prev_line = None for line in file: do stuff(line, prev_line) prev_line = line 
Awesome!
Thank you, guys!
Dance
Are you guys all in the same class? I still have the csv sample from some other thread about finding "Failed"

The pass/fail column is column F

How big is your ftor?

import sys path2csv = '/home/pedro/myPython/csv/csv/YE2531_20220609_074155_Tester1.csv' with open(path2csv) as mycsv: count = 1 data = mycsv.readlines() print('The size of data is', sys.getsizeof(data)) fails = [] for line in data: print('The size of line is', sys.getsizeof(line)) if 'Failed' in line: print('line', count, 'failed') print('of course, the previous line was', count-1) fails.append(count) count +=1 for f in fails: print('fail line number is', f)
That is funny!
No, we are not in the same class for sure.
I'm a 61-year-old guy trying the get some data from machines...

It is hard to learn anything if you are that old... Wink
Youngster!
Larz60+!
You are DA MAN
It's a shame you're on Windows. Otherwise, sounds like a job for grep and head probably.
I just asked if ftor is very big, maybe millions of lines, because then a function with yield may be better.

Then you need the experts here to design that, yield confuses me!
One can use itertools.pairwise()
for lineno, (prev_line, line) in enumerate(itertools.pairwise(ftor), 2): ... # do something with line and prev_line