Output last occurrence of match in file

Hi this is my problem statement
File 1 contains lines like this :

aaaa 1
aaaa 2
bbbb 1
bbbb 2
bbbb 3
cccc 1
cccc 2
dddd 1
dddd 2


File 2 contains these lines:

aaaa
cccc


I need to find from file 1 the matching lines for the last occurrence- so my output to be like

aaaa 2
cccc 2


I wrote this in Python

with open('C:\\Temp\\file2.txt', "r") as f1:
with open("C:\\Temp\\file1.txt", "r") as f2:
fo = open("C:\\Temp\\file3.txt", "w")

for x in range (len(list1)):
sample_list = []
i = 0
for i in range (len(list2)):
if list2[i][0:4] == list1[x][0:4]:
sample_list.append(list2[i][5:6])
else:
continue
if sample_list:
fo.write (list1[x][0:4] + " last occurrence was: " + sample_list[-1] + "\n")
else:


Just curious if this is a good approach to solving this problem or are there better ways?

• Does the order of the output lines matter? Jul 18 at 15:36

so [I want] my output to be like

aaaa 2
cccc 2


is not entirely correct, because you actually want your output to look like:

aaaa last occurrence was: 2
cccc last occurrence was: 2


Anyway, I don't think that fixed indexing is a very good idea for this application unless there are surprise spaces for which you haven't shown examples. You're probably better off just splitting.

For both the first and second files you read and store into memory all of the lines. You could take that opportunity to do some processing in-line with comprehensions, for instance creating a dictionary that naturally drops all but the last value for any given key. I don't think that range is well-applied here, and you also shouldn't have a nested loop.

Suggested

with open('file2.txt') as f:
needles = [line.rstrip() for line in f]

with open('file1.txt') as f:
haystack = dict(
line.split(maxsplit=2)
for line in f
)

with open('file3.txt', 'w') as out:
for needle in needles:
sample = haystack.get(needle)
if sample is None: