如何使用 python 在另一个文件中搜索文件的每一行?

How to search each line of a file in another file using 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 中是否有内置函数来执行此操作?

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

这解决了我的问题。

文件对象,当您 open 一个文件时得到它包含关于文件和文件中的当前位置的信息。在'r' mode1.

打开时默认位置为文件开头

当您从文件中读取(或写入)一些数据时,位置会移动。例如,f.read() 读取所有内容并移动到文件末尾。重复 f.read() 什么也读不到。

当您遍历文件时会发生类似的事情(例如 line in f2)。

我建议,除非文件有很多千兆字节,否则您应该读取这两个文件,然后在内存中执行其余逻辑,例如:

with open('expected_cmd.txt', 'r') as f1:
    lines1 = list(f1)

with open('%s.txt' %configured, 'r') as f2:
    lines2 = list(f2)

然后就可以实现逻辑了:

for line in lines1:
    if line not in lines2:
        print(line)

您已完整阅读 configured.txt 并通过删除 rcmd 中的行进行搜索。