簡體   English   中英

如何使用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 )時,會發生類似的事情。

我建議,除非文件的大小有很多 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)

您完全閱讀了configured.txt 並通過刪除rcmd 中的行來進行搜索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM