Python - 比较2个文件和输出差异

问题描述 投票:-1回答:2

我的目标是编写一个脚本来比较文件中的每一行,并根据这种比较,创建一个包含不在第二个文件中的文本行的新文件。

例如;

**File 1:** 

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

**File 2:**

Dan:50
Emma:32
Anne:43

新输出(文件3):

Bob:20
Brad:34

我知道如何做到这一点,但不完全是:

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:
            ....

我想我需要一些东西,然后比较每个文件的每一行的字符串[0],但从这一点来说我真的很无能为力。

任何帮助都将非常受欢迎。

python file compare output diff
2个回答
1
投票

这对我有用:

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)

您需要比较设置的readlines并找出file2中不存在的行。然后,您可以将这些行附加到新文件。


0
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.