在Python中比较两个文本文件

16
我需要比较两个文件并将不同的行重定向到第三个文件。 我知道可以使用diff命令获取差异。 但是,有没有用Python完成这个任务的方法?任何示例代码都会有所帮助。
4个回答

17

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;

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

-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
无论这段代码是否有效,它并没有真正解释如何完成问题所要求的任务。 - yoozer8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接