【Python】对比两个 txt 文件的不同

# 提前准备好三个txt文件
# 1.txt 和 2.txt 为对比文件
# diff.txt 为存储不同内容文件

# 以读取方式打开两个txt文件
f1 = open("1.txt","r")
f2 = open("2.txt","r")

# 读取两个txt文件
txt1 = f1.read()
txt2 = f2.read()
# 按行的方式读取txt文件
#txt1 = f1.readline()
#txt2 = f2.readline()

# 释放两个文件进程
f1.close()
f2.close()

# 将两个文件中内容按空格分隔开
line1 = txt1.split()
line2 = txt2.split()

# 以读取方式打开 diff.txt 文件
outfile = open("diff.txt", "w")

# 循环遍历1号文件中的元素
for i in line1:
	# 查看1中文件是否在2中存在
	if i not in line2:
		outfile.write(i)
outfile.write("Above content in 1. But not in 2.")
for j in line2:
	# 查看2中文件是否在1中存在
	if j not in line1:
		outfile.write(j)
outfile.write("Above content in 2. But not in 1.")
print("核对结束")


'''
file1 = "1.txt"
file2 = "2.txt"
f_diff = "diff.txt"
# ---------- 对比文件内容,输出差异
f1 = open(file1, "r")
f2 = open(file2, "r")
file1 = f1.readlines()
file2 = f2.readlines()
f1.close()
f2.close()
outfile = open(f_diff, "w")
flag = 0
outfile.write("file1独有的数据:\n")
for i in line1:
    if i not in line2:
        outfile.write(i)
        flag = 1
outfile.write("file2独有的数据:\n")
for i in line2:
    if i not in line1:
        outfile.write(i)
        flag = 1
outfile.close()
if flag == 1:
    print("数据存在差异,请仔细核对!")
'''

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhao-Jichao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值