【问题标题】:Get a specific line before specific line in txt file after comparison比较后获取txt文件中特定行之前的特定行
【发布时间】:2022-12-24 22:37:22
【问题描述】:

我正在比较 2 个 txt 文件,我想在差异行之前添加包含此行的接口名称,如下所示:

第一个文件包含:

!CfgFileCrc:f4fcebea
!Software Version V800R021C00SPC100
!Last configuration was updated at 2022-04-07 10:16:05 UTC 
!Last configuration was saved at 2022-04-09 21:00:41 UTC 
!MKHash 
info-center filter-id bymodule-alias system hwSecurityRisk
info-center loghost source LoopBack1
set service-mode forwarding-mode enhance
interface GigabitEthernet4/0/14
 shutdown
interface GigabitEthernet4/0/15
 negotiation auto
 undo shutdown
interface GigabitEthernet4/0/16
 negotiation auto
 undo shutdown

第二个文件包含:

!CfgFileCrc:f4fcebea
!Software Version V800R021C00SPC100
!Last configuration was updated at 2022-04-07 10:16:05 UTC
!Last configuration was saved at 2022-04-09 21:00:41 UTC 
!MKHash 
info-center filter-id bymodule-alias system hwSecurityRisk
info-center loghost source LoopBack1
set service-mode forwarding-mode enhance
interface GigabitEthernet4/0/14
 shutdown
interface GigabitEthernet4/0/15
 negotiation auto
 description CEM-Smart-Care-PS
 undo shutdown
interface GigabitEthernet4/0/16
 negotiation auto
 description CEM-Smart-Care-PS
 undo shutdown

代码如下:

def files(Devices):
 doc = open('C:/Users/Ahmed Shouaib/Desktop/Difference/test/10-4-2022/'+Devices+'.txt', 'r')
 dox = open('C:/Users/Ahmed Shouaib/Desktop/Difference/test/7-4-2022/'+Devices+'.txt', 'r')
 f1 = [x for x in doc.readlines()]
 f2 = [x for x in dox.readlines()]
 with open('C:/Users/Ahmed Shouaib/Desktop/Difference/test/result/' + Devices + '.txt', 'w') as new:
  GGG = ['CfgFileCrc', 'Last configuration was','MKHash' , 'username ftpuser password']
  for line in f1:
      if line not in f2 and not any(x in line for x in GGG):
          new.write("+"+line + '\n')

  GGG = ['CfgFileCrc','Last configuration was','MKHash','username ftpuser password']
  XX=1
  for line in f2:
      if line not in f1 and not any(x in line for x in GGG):
          if ( XX == 1):
           new.write('-' * 80 + '\n'+ '\n')
           XX = 0
          new.write("-"+line + '\n')
  doc.close()
  dox.close()

files('10.0.130.71')

代码结果如下:

+ description CEM-Smart-Care-PS

+ description CEM-Smart-Care-PS

我需要的代码结果:

interface GigabitEthernet4/0/15
+ description CEM-Smart-Care-PS

interface GigabitEthernet4/0/16
+ description CEM-Smart-Care-PS

【问题讨论】:

    标签: python difference txt


    【解决方案1】:

    不需要重新实现算法来查找差异,您可以使用difflib.ndiff(),只需要一些准备工作。我们只需要将属于接口的行传递给ndiff()

    我们可以使用返回接口名称的生成器函数,所有行都属于这个接口:

    def iter_interface(f):
        interface = ""
        lines = []
        for line in f:
            if interface:
                if line.startswith(" "):
                    lines.append(line.strip())
                else:
                    yield interface, lines
                    interface = ""
                    lines = []
            if line.startswith("interface"):
                interface = line.rstrip()
        if interface:
            yield interface, lines
    

    然后我们只打开这两个文件并使用我们的生成器函数迭代它们。如果两个文件中的接口名称相同,我们只需将行传递给ndiff() 并仅打印差异:

    from difflib import ndiff
    
    ...
    
    with open("file1.txt") as f1, open("file2.txt") as f2:
        for (interface_f1, lines_f1), (interface_f2, lines_f2) in 
                zip(iter_interface(f1), iter_interface(f2)):
            if interface_f1 == interface_f2:
                interface_printed = False
                for diff_line in ndiff(lines_f1, lines_f2):
                    if diff_line[0] != " ":
                        if not interface_printed:
                            print(interface_f1)
                            interface_printed = True
                        print(diff_line)
                if interface_printed:
                    print()
    

    使用您提供的两个文件示例,您将获得下一个输出:

    interface GigabitEthernet4/0/15
    + description CEM-Smart-Care-PS
    
    interface GigabitEthernet4/0/16
    + description CEM-Smart-Care-PS
    
    

    附言使用生成器函数可以让您不必将整个文件内容保存在内存中,因此这种方法应该适用于大文件。

    【讨论】:

      猜你喜欢
      • 2014-10-30
      • 2017-08-15
      • 2018-12-16
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多