在Python中比较两个文本文件

16 投票
4 回答
29023 浏览
提问于 2025-04-15 23:58

我需要比较两个文件,把不同的行写到第三个文件里。我知道可以用diff命令来找出不同的地方。但是,有没有办法用Python来实现这个呢?如果能给点示例代码就太好了。

4 个回答

4

如何在Python中比较两个文本文件?

当然可以,difflib这个库让这件事变得简单。

我们来做个演示:

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)

现在来看看差异。这里用到的 ostime 只是为了提供一个你文件最后修改时间的好时间戳,这个是可选的,传给 difflib.unified_diff 的参数也可以不加:

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

接下来,我们只需要打开文件,把它们的每一行(通过 f.readlines 获取)传给 difflib.unified_diff,然后把输出的列表用空字符串连接起来,最后打印结果:

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
          )))

这时会打印出:

--- 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

再说一次,你可以去掉所有那些标记为可选的行,这样就能得到没有时间戳的相同结果。

把不同的行重定向到第三个文件

与其打印出来,不如打开一个第三个文件来写入这些不同的行:

        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)

还有:

$ 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
6
#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;

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

17

可以看看 difflib 这个模块

这个模块提供了一些类和函数,用来比较序列。比如说,你可以用它来比较文件,它能以多种格式输出差异信息,包括 HTML 格式和上下文差异、统一差异等[...]

http://docs.python.org/library/difflib.html#difflib-interface 上有一个命令行的例子

撰写回答