我的目标是编写一个脚本来比较文件中的每一行,并根据此比较,创建一个新文件,其中包含第二个文件中不包含的文本行。
例如;
**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],但从这一点来说我真的很无能为力。
非常欢迎任何帮助。
答案 0 :(得分: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)
您需要比较设置的读取线并找出file2中不存在的行。然后,您可以将这些行附加到新文件中。
答案 1 :(得分: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