I have 2 text file that includes unique words and separated each line one word. I want to find how many line before specific word in file. Assume that
bread
pizza
pasta
tomato
is textfile1.
pizza
tomato
is textfile2.
I want to get
pizza 1
tomato 3
as output. I tried the code Python - Find line number from text file but because of my text files are huge it does not work correctly(textfile1 consists of 45999 line textfile2 consists of 2698 lines). How can solve this problem? Thank you..
You can read the words in textfile2
into a set, and then iterate through the lines of textfile1
with indices generated from enumerate
. Output the word with the current index if it is in the aforementioned set:
with open('textfile2') as file:
words = {line.rstrip() for line in file}
with open('textfile1') as file:
for index, line in enumerate(file):
word = line.rstrip()
if word in words:
print(word, index)