比较后获取txt文件中特定行之前的特定行

Get a specific line before specific line in txt file after comparison

我正在对 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

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

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

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

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


你可以帮助我的国家,检查my profile info