• Linux
  • FreeBSD
  • Networking
  • Python
  • AWS
  • WebDev
  • About Us

Compare two files and write only the differnce to another file in Python

Written by
Python Leave a Comment

This small python script will compare the two files : file1 and file2 and write the difference to a file diff.txt

with open('sample1file.txt', 'r') as file1:
       with open('sample2file.txt', 'r') as file2:
              difference = set(file1).difference(file2)
difference.discard('\n')

with open('diff.txt', 'w') as file_out:
    for line in difference:
       lines = line.split()
       lines.sort()
       file_out.write(line)

© Copyright 2020.TechieNix. All Rights Reserved.