Python對比兩個txt檔案的不同

2021-10-05 09:10:03 字數 1652 閱讀 6154

# 提前準備好三個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("資料存在差異,請仔細核對!")

'''

兩個檔案對比 C

public static bool filecompare string file1,string file2 int file1byte 0 int file2byte 0 using filestream fs1 new filestream file1,filemode.open fs2 n...

window下比較兩個txt檔案

我使用在c c 來寫百萬浮點數排序,用來比較輸出答案檔案與標準答案檔案的差異 首先將兩個需要比較的兩個txt檔案放到統一資料夾下面 例如我是放在f盤下的cmp檔案家 進入cmd命令視窗 win r出現對話方塊輸入cmd進入命令視窗 在cmd命令視窗中輸入f 即可進入f盤 接著輸入cd cmp cd進...

兩個JSON對比

需求 兩個json對比 目前有兩個json 型別的資料,和 對比出來的結構需要有,2 3 4 5 class bo public bo string rowno,string name public string getrowno public void setrowno string rowno ...