Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để so sánh hai tệp khác nhau từng dòng trong Python?


Thư viện chuẩn Python có một mô-đun dành riêng cho mục đích tìm kiếm sự khác biệt giữa các chuỗi / tệp. Để có được một khác biệt bằng cách sử dụng thư viện difflib, bạn có thể chỉ cần gọi hàm united_diff trên đó. Ví dụ:Giả sử bạn có 2 tệp, tệp1 và tệp2 với nội dung sau -

file1:
Hello
People
of
the
world
file2:
Hello
People
from
India

Ví dụ

Bây giờ, để sử dụng mã khác, hãy sử dụng mã sau -

import difflib
with open('file1') as f1:
    f1_text = f1.read()
with open('file2') as f2:
    f2_text = f2.read()
# Find and print the diff:
for line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''):
    print line

Đầu ra

Điều này sẽ đưa ra kết quả -

--- file1
+++ file2
@@ -1,5 +1,4 @@
 Hello
 People
-of
-the
-world
+from
+India