变量在嵌套循环内丢失引用

时间:2016-06-19 19:40:20

标签: python loops scope

我的变量tag在输入嵌套for时失去了引用:

file_with_all_tags = open("tags.txt", "r")
origem = open("origem.html", "r")

for tag in file_with_all_tags:

    final_file_name = "tag-" + tag + ".html"
    final_file = open(final_file_name, "w")

    for line in origem:
        if tag in line: # HERE THE VARIABLE 'TAG' IS EMPTY
            final_file.write(line)

    final_file.close()

origem.close()
file_with_all_tags.close()

1 个答案:

答案 0 :(得分:0)

问题解决了!实际上我对文件" origem.html"的迭代很累。我不得不将open()和close()函数移动到循环内部。多谢你们!谢谢@rrauenza!