Skip to content
Advertisement

How do I find duplicates and print the line in a text file?

I am trying to go through a .txt and find duplicate names in the file, but also print out the line that duplicate is located on.

This is what I have so far for finding the duplicate names:

JavaScript

But I am unsure of how to show what line they are located on. I read about finding a keyword in file but I don’t know how to put it in this code, I tried:

JavaScript

And that just printed out the duplicates.

Advertisement

Answer

Just add the enumerate to the place where you are reading the line in the first place.

JavaScript

This just collects duplicates while reading the file, so we avoid looping over the same data several times. If you want to keep track of where the original occurrence was, that will be easy too (just add another dict where the key is the c value and the value is the line number where it was first seen).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement