for-loop 被跳过,我不明白为什么 - Python

The for-loop is skipped and I don't understand why - Python

我很难理解为什么我的 for-loop 在代码第二次通过 while-loop 时被跳过。第一轮一切都很好。

k = 0
with open("Result.txt", "r") as ParseOutput:
    while k < num_lines:                                # num lines in test file = 12
        print("k: " + str(k))
        for line in islice(ParseOutput, k, k+100000):
            print("k in islice: " + str(k))
            field_list = []
            fields = line.strip("\n")
            fields = fields.split("\t")
            field_list.append(fields)
            query_plasmid = field_list[0][0]
            print("Query Plasmid: " + str(query_plasmid))

        l = k

        for m, line in enumerate(islice(ParseOutput, l, l+100000)):
            if l < 100000:
                print("if l: " + str(m))
                field_list = []
                fields = line.strip("\n")
                fields = fields.split("\t")
                field_list.append(fields)

                next_plasmid = field_list[0][0]
                print("Next Plasmid: " + str(next_plasmid) + "  l: " + str(l))

                if not str(query_plasmid) == str(next_plasmid):
                    query_plasmid_index = UniqueID_List.index(query_plasmid)
                    Start_line_list[query_plasmid_index] = k
                    End_line_list[query_plasmid_index] = m
                    New_start_line = m+1
                    print("Start line: " + str(k))
                    print("End line: " + str(m))
                    print("New_start_line: " + str(New_start_line))

                    l = 999999
                    print("l: " + str(l))

        k = k+1

打印命令仅供我控制。这是脚本的输出:

k: 0
k in islice: 0
Query Plasmid: DA_000001
if l: 0
Next Plasmid: DA_000001 l: 0
if l: 1
Next Plasmid: DA_000001 l: 0
if l: 2
Next Plasmid: DA_000001 l: 0
if l: 3
Next Plasmid: DA_000002 l: 0
Start line: 0
End line: 3
New_start_line: 4
l: 999999
k: 1
k: 2
k: 3
k: 4
k: 5
k: 6
k: 7
k: 8
k: 9
k: 10
k: 11

正如标题所说,我不明白为什么 k>0 会跳过 for-loop。感谢您的帮助或任何其他想法!

最好的, 菲利普

PS:我希望有一个带有列表的解决方案,但不幸的是我的文件太大了,我什至无法枚举没有 运行 的行进入内存错误。因此,使用硬编码数字的解决方法。

我认为您从第一个循环开始就阅读了整个文件。 因为您到达了文件描述符的 EOF 'ParseOutput',所以您的两个 for 循环都没有要读取的行。

在你的循环结束时(或者如果你想的话开始),你需要添加:

ParseOutput.seek(0)

这将使您的文件描述符指向文件的开头。