逐行比较两个文件数据,并将它们之间的差异仅存储在另一个文件中

时间:2019-06-14 17:25:52

标签: python-2.7 file

我有2个文本文件file1和file2。我正在尝试逐行比较两个文件,然后将仅打印不匹配/差异的内容打印/写入到第三个文件。

我已经尝试了difflib.unified_diff,但是它为输出提供了很多不必要的信息。因此,仅需打印不在file2中的file1的文本。 以下是我尝试的代码。

def file_byline_comp(f1,f2,f3):
    # Read the first line from the files
    file1= open(f1)
    file2= open(f2)
    result_output_file= open(f3,'w')
    file1_line = file1.readline()
    file2_line = file2.readline()

    # Initialise counter for line number
    line_no = 1

    # Loop if either file1 or file2 has not reached EOF
    while file1_line != '' or file2_line != '':

        # Strip the leading whitespaces
        file1_line = file1_line.rstrip()
        file2_line = file2_line.rstrip()

        # Compare the lines from both file
        if file1_line != file2_line:

            if file2_line == '' and file1_line != '':
               # print("Line-%d" % line_no, file1_line)
                print("Line-%d" % line_no)

                print difflib.unified_diff(file1_line, file2_line,fromfile='f1', tofile='f2',lineterm='')
                result_output_file.write("Line-%d " % (line_no))
                result_output_file.write(file1_line)
            # otherwise output the line on file1 
            elif file1_line != '':
                #print("Line-%d" % line_no, file1_line)
                print("Line-%d" % line_no)
                for line in difflib.unified_diff(file1_line, file2_line,fromfile='f1', tofile='f2',lineterm=''):
                    print line

                result_output_file.write("Line-%d " % (line_no))
                result_output_file.write(file1_line)

0 个答案:

没有答案