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:


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:
    list1 = f1.readlines()
with open("C:\\Temp\\file1.txt", "r") as f2:
    list2 = f2.readlines()
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]:
    if sample_list:
        fo.write (list1[x][0:4] + " last occurrence was: " + sample_list[-1] + "\n")
        fo.write( list1[x][0:4] + " was not found" + "\n")

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

  • 1
    \$\begingroup\$ Does the order of the output lines matter? \$\endgroup\$
    – Reinderien
    Jul 18 at 15:36

1 Answer 1


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.


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

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

with open('file3.txt', 'w') as out:
    for needle in needles:
        sample = haystack.get(needle)
        if sample is None:
            print(needle, 'was not found', file=out)
            print(needle, 'last occurrence was:', sample, file=out)
  • \$\begingroup\$ Thanks for your response but I absolutely don't appreciate being called a liar- where I come from to accuse somebody of lying is pretty serious. Is the actual program output slightly different from my problem statement? I don't disagree and I accept responsibility- but that's a long way from accusing me of prevarication. \$\endgroup\$
    – medh ansu
    Jul 19 at 12:47
  • \$\begingroup\$ @medhansu I'm being fecetious, but I'm sorry for offending you. Update your question to be more accurate and I'll adjust accordingly. \$\endgroup\$
    – Reinderien
    Jul 19 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.