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

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.

解决方案

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值