Python - Compare 2 files and output differences

前端 未结 2 725
悲&欢浪女
悲&欢浪女 2021-01-16 06:42

I\'m aiming to write a script that will compare each line within a file, and based upon this comparison, create a new file containing the lines of text which aren\'t in the

2条回答
  •  我在风中等你
    2021-01-16 07:20

    This is working for me:

    def compare(File1,File2):
        with open(File1,'r') as f:
            d=set(f.readlines())
    
    
        with open(File2,'r') as f:
            e=set(f.readlines())
    
        open('file3.txt','w').close() #Create the file
    
        with open('file3.txt','a') as f:
            for line in list(d-e):
               f.write(line)
    

    You need to compare the readlines set and find out lines that are not present in file2. You can then append these lines to the new file.

提交回复
热议问题