0

Can anyone help me with forming programme code which check matching word and delete that line that didn't have matching word

in a text file

22nd Nov 2020, 9:45 AM
Himanshu Kurche
Himanshu Kurche - avatar
2 ответов
0
path = "sample.txt" word = "my word" Open file and copy the lines lines = [] with open(path, "r") as f: lines += f.readlines() delete all the lines that doesn't have the matching word lines = list(filter(lambda line: word not in line, lines)) #Use the filterd list as you want print(lines) ----------------------------- or you can use a for loop instead of the filter function for i in range(len(lines)): if word not in lines[i]: lines.remove(i)
22nd Nov 2020, 10:11 AM
Yamen Ghozlan
Yamen Ghozlan - avatar
+ 6
Something like this? for line in lines: line = line if word in line else ""
22nd Nov 2020, 9:59 AM
David Ashton
David Ashton - avatar