pythonfileduplicates

How to output the unique elements from one text file into another


I have a text file called sample.txt:

abc  
abc
egf
abc 
xyz
efg
xyz
efg

I want the to find and store the unique elements in another text file called output.txt:

abc
efg
xyz
egf

Solution

  • Assuming output order is not important

    with open('input_file','r') as f:                                                                                                                                                                                                                                                 
        distinct_content=set(f.readlines())                                                                                                                                                                                                                                                   
    
    to_file=""                                                                                                                                                                                                                                                                       
    for element in distinct_content:                                                                                                                                                                                                                                                               
        to_file=to_file+element                                                                                                                                                                                                                                                           
    with open('output_file','w') as w:                                                                                                                                                                                                                                                  
        w.write(to_file) 
    

    output:

    efg
    egf
    xyz
    abc