首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较后,在txt文件中的特定行之前获取一条特定行。

比较后,在txt文件中的特定行之前获取一条特定行。
EN

Stack Overflow用户
提问于 2022-04-10 10:24:59
回答 1查看 58关注 0票数 1

我正在对两个txt文件进行比较,我想在差异行之前添加接口的名称,其中包含如下所示的一行:

第一个文件包含:

代码语言:javascript
复制
!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

第二个文件包含:

代码语言:javascript
复制
!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

代码如下:

代码语言:javascript
复制
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')

代码结果如下:

代码语言:javascript
复制
+ description CEM-Smart-Care-PS

+ description CEM-Smart-Care-PS

所需的代码结果:

代码语言:javascript
复制
interface GigabitEthernet4/0/15
+ description CEM-Smart-Care-PS

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-10 12:03:51

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

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

代码语言:javascript
复制
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()并只打印差异:

代码语言:javascript
复制
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()

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

代码语言:javascript
复制
interface GigabitEthernet4/0/15
+ description CEM-Smart-Care-PS

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

使用生成器函数的P.S.允许您不将整个文件内容保存在内存中,因此该方法应该可以很好地处理大型文件。

你可以帮助我的国家,检查。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71815685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档