Find unique lines from two .txt files and store the unique new lines in Python

In this tutorial, we will learn how to find only the unique lines from the two .txt files (text files) in Python. We can also say that we will remove the lines that exist in both of the text (.txt) files and store the new lines in another .txt file using Python.

For example, assume that we have two .txt files: a.txt and b.txt

a.txt consist of these lines

hello
codespeedy
I am happy

and the second .txt file which is b.txt contains these lines:

hello
codespeedy
I am happy
Are you happy?
I like you

Now we will make a Python program that will only show the lines which are not present in the first text file which is a.txt.

For my example, my program should give an output like this below:

Are you happy?
I like you

We will be storing the final output in a separate text file.

But you can modify the program as per your requirement or ask me if you need something modified in the comment section.

first_file_list = open('a.txt','r').readlines()
second_file_list = open('b.txt','r').readlines()

new_lines = []
for item in second_file_list:
  if item not in first_file_list:
    new_lines.append(item)

with open('c.txt','w') as file_out:
    for line in new_lines:
        file_out.write(line)

Output:

It will create a new file c.txt and it will contain only the lines which are not in a.txt but are in b.txt.

If there is already a file c.txt then it will just update the file.

You can check these: Find line number of a specific string or substring or word from a .txt file in Python

Leave a Reply

Your email address will not be published. Required fields are marked *