DIFF循环将差异写入多个文件

时间:2016-05-31 13:49:19

标签: diff

创建以下代码是为了比较路由器配置更改的快照之前和之后,以确保更改完整性。代码“有效”,因为它确实创建了一个特定于设备名称的文件,并且捕获了前后更改文件的差异并将其写入文件。但是,代码的问题是每个'set'文件的'差异'被附加到每个后续的diff文件中;如果存在20组文件,则最后一个diff文件将包含所有20个差异。代码背后的想法是捕获单个文件中每个设备的差异。我不确定我在代码中缺少什么。 for循环通过device_list正确枚举并关闭。我认为问题在于捕获的'diff'信息在写入特定文件后没有清除,因此它只是附加到下一个文件。我无法“看到”如何纠正它。

我感谢任何建议/指导。很抱歉这么粗鲁的问题描述。

    for n, elem in enumerate(device_list):
        prefilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "PRE_TEST_" + elem + '.txt')
        postfilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "POST_TEST_" + elem + '.txt')
        difffilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "DIFF_" + elem + '.txt')

        with open(prefilename, 'r') as f:
            h = f.readlines()
            for line in h:
                if regex_time_stamp.search(line) is not None:
                    new_line = re.sub(regex_time_stamp, '', line)
                    pre_list.append(new_line)
                else:
                    pre_list.append(line)

        with open(postfilename, 'r') as f:
            h = f.readlines()
            for line in h:
                if regex_time_stamp.search(line) is not None:
                    new_line = re.sub(regex_time_stamp, '', line)
                    post_list.append(new_line)
                else:
                    post_list.append(line)

        open(difffilename, 'w').close()  # Create the file

        with open(difffilename, 'a') as f:
            diff = difflib.unified_diff(pre_list, post_list, fromfile=prefilename, tofile=postfilename)
            f.writelines(diff)

2 个答案:

答案 0 :(得分:0)

在外部'for'循环中,在打开任何文件之前,看起来你应该清除pre_list和post_list。它们只是在每个循环中累积。

答案 1 :(得分:0)

    for n, elem in enumerate(device_list):

        pre_list = []  #clear contents of pre_list file for reuse
        post_list = []  #clear contents of post_list file for reuse

        prefilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "PRE_TEST_" + elem + '.txt')
        postfilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "POST_TEST_" + elem + '.txt')
        difffilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "DIFF_" + elem + '.txt')