【问题标题】:How to search each line of a file in another file using python?如何使用python在另一个文件中搜索文件的每一行?
【发布时间】:2020-10-11 17:42:31
【问题描述】:

我的 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 中是否有一个内置函数可以做到这一点?

【问题讨论】:

    标签: python file with-statement


    【解决方案1】:
    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
    

    这解决了我的问题。

    【讨论】:

    • 没错。您现在只阅读了一次f2,因此您避免了最初的问题。
    【解决方案2】:

    open 文件时获得的文件对象包含有关文件和文件中当前位置的信息。在'r' mode1 中打开文件时,默认位置是文件的开头。

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

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

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

    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)
    

    【讨论】:

      【解决方案3】:

      您完全阅读了配置的.txt,并通过删除 rcmd 中的行来进行搜索。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多