# 提前准备好三个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("数据存在差异,请仔细核对!")
'''
【Python】对比两个 txt 文件的不同
于 2020-04-23 13:52:54 首次发布