簡體   English   中英

Python:為什么我的循環不會迭代?

[英]Python: Why won't my loop iterate?

我有一個簡單的python代碼,它打開兩個文件,並循環遍歷一個文件中的每個字符串,在另一個文件中查找匹配的字符串(或字符串的一部分)。 如果找到它,則應將該行寫入文件。 由於某種原因,它沒有迭代。 這是我的代碼:

out = open("outputfile.txt", "w")
with open("inputfile1.txt", "r") as f:
    with open("inputfle2.txt", "r") as map:
        for line in f:
            for mline in map:
                if line[0:6] in mline:
                    out.write(line)

由於某種原因,結果輸出文件僅包含一行。 我已經檢查了這一行,它是正確的,所以代碼正在執行我想要的操作,但是由於某種原因,循環沒有遍歷兩個文件。 我知道有一個明顯的解決方案,但是經過數小時的搜索和修改我的代碼並沒有產生任何結果。

當該line到達文件f的第二行時, mline已經讀取了map所有行並耗盡了生成器。

您需要緩存map的內容:

out = open("outputfile.txt", "w")

with open("inputfle2.txt", "r") as map:
    map_lines = map.readlines()

with open("inputfile1.txt", "r") as f:
    for line in f:
        for mline in map_lines:
            if line[0:6] in mline:
                out.write(line)

暫無
暫無

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

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