Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок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
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)
+ 6
Something like this?
for line in lines:
line = line if word in line else ""