比较后在TXT文件中在特定行之前获取特定行

发布于 2025-01-20 07:18:59 字数 2514 浏览 0 评论 0原文

我正在进行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

I'm doing comparison between 2 txt files and i want to add before the difference lines the name of interface which contains this line to be like below :.

First file contains :

!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

Second file contains :

!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

Code is as below :

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')

code result is like below :

+ description CEM-Smart-Care-PS

+ description CEM-Smart-Care-PS

The code result which i need to be :

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青丝拂面 2025-01-27 07:18:59

不需要重新实现算法来查找差异,您可以使用 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

PS 使用生成器函数允许您不将整个文件内容保留在内存中,因此此方法对于大文件应该可以正常工作。

It's not necessary to reimplement algorithm to find differences, you can use difflib.ndiff(), just some preparation required. We need to pass to ndiff() only lines which belongs to interface.

We can use generator function which returns interface name and all lines belongs to this interface:

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

Then we just open both files and iterate over them using our generator function. If interface names are equal in both files we simply pass lines to ndiff() and print only differences:

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()

Using two file samples you provided you will get next output:

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

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

P.S. Using generator function allows you to not keep entire file content in memory, so this method should work fine with large files.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文