Show different lines in files

Viewed 54

I have found a script which shows different lines in the file NEW.txt which do not exist in OLD.txt file. It works fine, but the problem is that script is messing the lines order when I get the output. This is the script:

with open(r'C:\Users\AMB\NEW.txt') as f, open(r'C:\Users\AMB\OLD.txt') as f2:
    lines1 = set(map(str.rstrip, f))
    s = str(lines1.difference(map(str.rstrip, f2)))                                                   
s = s.replace(',', '\n').replace("'", '').replace("{", '').replace("}", '')

print(s)  

So let's suppose that this is the OLD.txt content:

aaaaaaaaaaaa
cccccccccccc
eeeeeeeeeeee

And this is the NEW.txt content:

aaaaaaaaaaaa
bbbbbbbbbbbb
cccccccccccc
dddddddddddd
eeeeeeeeeeee
hhhhhhhhhhhh

I would like to get this output:

bbbbbbbbbbbb
dddddddddddd
hhhhhhhhhhhh

But I am getting a random line order, for example:

dddddddddddd
bbbbbbbbbbbb
hhhhhhhhhhhh

(the output is random, and not always the same)

Is there a way to keep the order for output lines in NEW.txt file? Thanks in advance.

1 Answers

You can remove the set and do all the operations using list.

See this link for more help.

Solution:

s = ""
with open(r'C:\Users\AMB\NEW.txt') as f, open(r'C:\Users\AMB\OLD.txt') as f2:
    lines1 = list(map(str.rstrip, f)) #list of words in f
    lines2 = list(map(str.rstrip, f2)) #list of words in f2
    
    #finds the difference between both lists
    diff = [i for i in lines1 + lines2 if i not in lines1 or i not in lines2]
    
    for words in diff:
        s = s + words + '\n' #Appending all words to form a single string

s = s.rstrip() #remove last line whitespace
print(s) 
Related