Python“for ... in”嵌套循环不能按预期工作

时间:2016-02-02 18:33:56

标签: python

我想在Python上进行嵌套循环,但最外层的循环不会迭代 我的代码

file1 = open(textFile1.txt)
file2 = open(textFile2.txt)
for line1 in file1:
    for line2 in file2:
        print line1

它仅打印line1的第一行,其中不会遍历file1

你可以指出我的错误吗? 我要做的是使用

匹配line1line2
if re.search(line1, line2):

所以我确实需要最外层的循环。 您会建议其他什么解决方案?

编辑: file1的内容

hello
bello

file2的内容

hello world
bello world
hello yellow
bello yellow
bellow yellow

我想grep文件2中包含file1

中的单词的任何行

1 个答案:

答案 0 :(得分:1)

打开的文件充当迭代器。一旦你迭代它一次,即在第一次运行外循环之后,它就会耗尽。

相反,您可以重新打开文件,将其内容缓存在列表中,或使用file2.seek(0)重置位置。

相关问题