首页 > 解决方案 > 如何使用python在另一个文件中搜索文件的每一行?

问题描述

我的expected_cmd.txt(比如f1)是

mpls ldp
snmp go
exit

我的configured.txt(比如f2)是

exit

这是我正在尝试的代码,在 f2 中搜索 f1 的所有行

with open('expected_cmd.txt', 'r') as rcmd, open('%s.txt' %configured, 'r') as f2:
    for line in rcmd:
            print 'line present is ' + line
            if line in f2:
                    continue
            else:
                    print line

所以基本上我试图从第一个文件中打印第二个文件中不存在的行。但是使用上面的代码,我得到的输出为

#python validateion.py
line present is mpls ldp

mpls ldp

line present is snmp go 

snmp go 

line present is exit

exit

不知道为什么要打印exit匹配的内容。

另外我想知道是否有内置函数可以在 python 中执行此操作?

标签: pythonfilewith-statement

解决方案


with open('%s.txt' %configured,'r') as f2:
    cmds = set(i.strip() for i in f2)
with open('expected_cmd.txt', 'r') as rcmd:
    for line in rcmd:
            if line.strip() in cmds:
                    continue
            else:
                    print line

这解决了我的问题。


推荐阅读