2010-06-15 38 views
13

Tôi cần so sánh hai tệp và chuyển hướng các dòng khác nhau đến tệp thứ ba. Tôi biết bằng cách sử dụng lệnh diff tôi có thể nhận được sự khác biệt. Nhưng, có cách nào để làm điều đó trong python? Bất kỳ mẫu mã sẽ rất hữu íchSo sánh hai tệp văn bản trong python

Trả lời

16

séc ra difflib

Module này cung cấp các lớp và chức năng để so sánh chuỗi. Nó thể được sử dụng ví dụ để so sánh tập tin, và có thể tạo ra sự khác biệt thông tin trong các định dạng khác nhau, bao gồm HTML và bối cảnh và thống nhất diffs [...]

Một dòng lệnh ví dụ trong http://docs.python.org/library/difflib.html#difflib-interface

-3
import sys 
if len(sys.argv) !=3 : 
    print "usage:" + sys.argv[0] + " bla bla" 
    exit 
elif len(sys.argv) == 3: 
    file1 = set((x for x in open(sys.argv[1]))) 
    file2 = set((x for x in open(sys.argv[2]))) 
    file3 = file2.difference(file1) 
    file4 = file1.difference(file2) 
    str1="file1-contains but file2 not \n" 
    str2="file2-contains but file1 not\n" 
    FILE = open('file3','w') 
    FILE.writelines(str2) 
    FILE.writelines(file3) 
    FILE.writelines(str1) 
    FILE.writelines(file4) 
+2

Bất kể mã này có hoạt động hay không, nó thực sự không giải thích cách thực hiện mũ câu hỏi yêu cầu. – yoozer8

4
#compare 2 text files. 

test1filehandle = open("test1.txt", "r") #creating a file handle 
test2filehandle=open("test2.txt","r") #creating a file handle to read 
test3filehandle=open("test3.txt","w") #creating a file handle to write 
test1list= test1filehandle.readlines() #read the lines and store in the list 
test2list=test2filehandle.readlines() 
k=1 
for i,j in zip(test1list,test2list): #zip is used to iterate the variablea in 2 lists simultaneoously 
    if i !=j: 
     test3filehandle.write("Line Number:" +str(k)+' ') 
     test3filehandle.write(i.rstrip("\n") + ' '+ j) 
    k=int(k) 
    k=k+1; 
+1

Tại sao lại là downvote? Có thể giải thích mã của bạn Rekha? –

2

So sánh hai tập tin văn bản trong python?

Chắc chắn, difflib giúp bạn dễ dàng.

Hãy thiết lập một bản demo:

f1path = 'file1' 
f2path = 'file2' 
text1 = '\n'.join(['a', 'b', 'c', 'd', '']) 
text2 = '\n'.join(['a', 'ba', 'bb', 'c', 'def', '']) 
for path, text in ((f1path, text1), (f2path, text2)): 
    with open(path, 'w') as f: 
     f.write(text) 

Bây giờ để kiểm tra một diff. Các dòng có sử dụng ostime được chỉ đơn thuần dùng để cung cấp một dấu thời gian khá cho thời gian qua tập tin của bạn đã được sửa đổi, và hoàn toàn không bắt buộc, và là đối số tùy chọn để difflib.unified_diff:

# optional imports: 
import os 
import time 
# necessary import: 
import difflib 

Bây giờ chúng ta chỉ cần mở các tập tin, và thông qua một danh sách các dòng họ (từ f.readlines) để difflib.unified_diff, và tham gia vào đầu ra danh sách với một chuỗi rỗng, in kết quả:

with open(f1path, 'rU') as f1: 
    with open(f2path, 'rU') as f2: 
     readable_last_modified_time1 = time.ctime(os.path.getmtime(f1path)) # not required 
     readable_last_modified_time2 = time.ctime(os.path.getmtime(f2path)) # not required 
     print(''.join(difflib.unified_diff(
      f1.readlines(), f2.readlines(), fromfile=f1path, tofile=f2path, 
      fromfiledate=readable_last_modified_time1, # not required 
      tofiledate=readable_last_modified_time2, # not required 
     ))) 

mà in:

--- file1  Mon Jul 27 08:38:02 2015 
+++ file2  Mon Jul 27 08:38:02 2015 
@@ -1,4 +1,5 @@ 
a 
-b 
+ba 
+bb 
c 
-d 
+def 

Một lần nữa, bạn có thể xóa tất cả các dòng được khai báo tùy chọn/không bắt buộc và nhận các kết quả tương tự nếu không có dấu thời gian.

chuyển hướng dòng khác nhau vào một tập tin thứ ba

thay vì in ấn, mở một tập tin thứ ba để viết các dòng:

 difftext = ''.join(difflib.unified_diff(
      f1.readlines(), f2.readlines(), fromfile=f1path, tofile=f2path, 
      fromfiledate=readable_last_modified_time1, # not required 
      tofiledate=readable_last_modified_time2, # not required 
     )) 
     with open('diffon1and2', 'w') as diff_file: 
      diff_file.write(difftext) 

và:

$ cat diffon1and2 
--- file1  Mon Jul 27 11:38:02 2015 
+++ file2  Mon Jul 27 11:38:02 2015 
@@ -1,4 +1,5 @@ 
a 
-b 
+ba 
+bb 
c 
-d 
+def