如何在 Python 中逐行比較兩個不同的檔案?
本教程介紹了用於比較兩個檔案的各種 Python 比較技術。我們將介紹如何透過使用可用的模組、讀取兩個檔案並逐行比較它們來執行此常見任務。
在 Python 中,比較兩個檔案可以透過多種方式完成。
逐行比較兩個文字檔案
使用 open() 函式讀取兩個文字檔案中的資料,我們可以比較它們包含的資訊。open() 函式將搜尋本地目錄並可能讀取它們。
示例
在此示例中,我們將對比兩個包含 python 資料的檔案。我們被告知這兩個 python 檔案可能不相同。Python 將為我們檢查這些檔案。可以使用 readlines() 方法從 python 檔案中提取行。
file1 = open('D:\Work TP/moving files.py', 'r') file2 = open('D:\Work TP/mysql_access.py', 'r') File3 = open('D:\Work TP/trial.py', 'w') for line1 in file1: for line2 in file2: if line1 == line2: File3.write("%s\n" %(line1)) File3.close() file1.close() file2.close()
在提取資料後,使用 for 迴圈逐行比較檔案。如果行不匹配,則透過訊息通知使用者發生不匹配的位置。為了方便使用者查詢不同的行,我們將包含資料本身。
輸出
以下是上述程式碼的輸出 -
Line 1 doesn't match. ------------------------ File1: # importing the modules File2: import mysql.connector Line 2 doesn't match. ------------------------ File1: import os File2: sampleDB=mysql.connector.connect(host='localhost',user='root',password='password',database='textx') Line 3 doesn't match. ------------------------ File1: import shutil File2: #print (sampleDB.connection_id) Line 4 doesn't match. ------------------------ File1: # Providing the folder path File2: cur=sampleDB.cursor() Line 5 doesn't match. ------------------------ File1: origin = 'C:\Users\Lenovo\Downloads\Works\' File2: s="CREATE TABLE novel(novelid integer(4),name varchar(20),price float(5,2))" Line 6 doesn't match. ------------------------ File1: target = 'C:\Users\Lenovo\Downloads\Work TP\' File2: cur.execute(s)
使用 filecmp 模組
filecmp 模組使在 Python 中處理檔案成為可能。此模組專門用於比較兩個或多個檔案之間的資料。我們可以使用 filecmp.cmp() 方法來實現這一點。如果檔案匹配,此函式將返回 True;否則,將返回 False。
示例
以下是使用 filecmpule 的示例 −
import filecmp import os # notice the two backslashes File1 = "D:\Work TP\moving files.py" File2 = "D:\Work TP\trial.py" def compare_files(File1,File2): compare = filecmp.cmp(File1,File2) if compare == True: print("The two files are the same.") else: print("The two files are different.") compare_files(File1,File2)
輸出
以下是上述程式碼的輸出 -
The two files are different.
使用 difflib 模組
要比較文字並識別它們之間的差異,請使用 difflib 包。此 Python 3 模組已預先打包到語言中。它具有許多用於比較文字樣本的有用功能。
首先,我們將使用 unified diff() 函式識別兩個資料檔案之間的差異。接下來,我們將比較這些檔案。
示例 1 - 使用 unified-diff()
在下面的示例中,使用 with 語句讀取檔案資料。Python with 語句允許我們安全地開啟和讀取檔案 -
import difflib with open("D:\Work TP/moving files.py",'r') as file1: file1_info = file1.readlines() with open("D:\Work TP/trial.py",'r') as file2: file2_info = file2.readlines() diff = difflib.unified_diff( file1_info, file2_info, fromfile="file1.py", tofile="file2.py", lineterm='') for lines in diff: print(lines)
輸出
以下是上述程式碼的輸出 -
--- file1.py
+++ file2.py
@@ -1,12 +0,0 @@
-# importing the modules
-import os
-import shutil
-# Providing the folder path
-origin = 'C:\Users\Lenovo\Downloads\Works\'
-target = 'C:\Users\Lenovo\Downloads\Work TP\'
-# Fetching the list of all the files
-files = os.listdir(origin)
-# Fetching all the files to directory
-for file_name in files:
- shutil.copy2(origin+file_name, target+file_name)
-print("Files are copied succesfully")
示例 2 - 使用 differ()
在 difflib 庫中,有一個名為 Differ 的類可用於比較檔案差異。此類用於比較文字行組並生成增量或差異。
以下是一個使用 differ() 方法逐行比較兩個不同檔案的示例 -
from difflib import Differ with open('D:\Work TP/moving files.py') as file1, open('D:\Work TP/trial.py') as file2: vary = Differ() for lines in vary.compare(file1.readlines(), file2.readlines()): print(lines)
輸出
以下是上述程式碼的輸出 -
- # importing the modules
- import os
- import shutil
- # Providing the folder path
- origin = 'C:\Users\Lenovo\Downloads\Works\'
- target = 'C:\Users\Lenovo\Downloads\Work TP\'
- # Fetching the list of all the files
- files = os.listdir(origin)
- # Fetching all the files to directory
- for file_name in files:
- shutil.copy2(origin+file_name, target+file_name)
- print("Files are copied succesfully")
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP