Python - Compare 2 files and output differences

会有一股神秘感。 提交于 2019-12-30 07:51:51

问题


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 second file.

For example;

**File 1:** 

Bob:20 
Dan:50 
Brad:34 
Emma:32 
Anne:43

**File 2:**

Dan:50
Emma:32
Anne:43

The new output (File 3):

Bob:20
Brad:34

I have some idea of how this needs to be done, but not exactly:

def compare(File1,File2):
   with open(File1, "a") as f1:
       lines = f1.readlines()
       string = line.split(':')
   with open(File2, "a") as f2:
       lines = f2.readlines()
       string2 = line.split(':')
       if string[0] == string[1]:
           with open("newfile2.txt", "w") as f3:
            ....

I think I need something along the lines of this and then to compare the string[0] from each line of each file but I'm really clueless from this point.

Any help would be extremely welcomed.


回答1:


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.




回答2:


with open("H:/Ast/Hpa.java", encoding="utf8") as f:
    with open("G:/Soft_install/Hpa.java", encoding="utf8") as fe:
        for line in f:
            for linefe in fe:
                if (line != linefe):
                    print(line)
                    break
                else:
                    break


来源:https://stackoverflow.com/questions/28213525/python-compare-2-files-and-output-differences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!