Python3 - 对于字典读取文件行中的键,不适用于所有项目

Python3 - For key in dict read file lines, doesn't working with all items

我查看了文档和一些问题,但没有找到类似的东西。

我有一本字典,对于每个项目,我需要循环整个文件并检索一些特定值。交互作用于 DICT -> LIST,但当尝试使用文件时它不起作用。

代码:

file = open(sys.argv[1], newline='')

print("DICT - FILE")
d= {1:"a",2:"b",3:"c"}
for item in d:
    print("Loop over item =", item)
    for n, line in enumerate(file):
        print("Do something on line =", n)

file.close()

print()

print("DICT - LIST")
l1 = [[1,2,3],[4,5,6],[7,8,9]]
for item in d:
    print("Loop over item =", item)
    for n in l1:
        print("Do something on list item =", n)

输出:

DICT - FILE
Loop over item = 1
Do something on line = 0
Do something on line = 1
Do something on line = 2
Do something on line = 3
Do something on line = 4
Loop over item = 2
Loop over item = 3

DICT - LIST
Loop over item = 1
Do something on list item = [1, 2, 3]
Do something on list item = [4, 5, 6]
Do something on list item = [7, 8, 9]
Loop over item = 2
Do something on list item = [1, 2, 3]
Do something on list item = [4, 5, 6]
Do something on list item = [7, 8, 9]
Loop over item = 3
Do something on list item = [1, 2, 3]
Do something on list item = [4, 5, 6]
Do something on list item = [7, 8, 9]

有人能弄清楚为什么 DICT - FILE 方法在 Loop over item = 2 后不再读取行吗?

一个文件就是一个迭代器。 enumerate(file) 耗尽了迭代器,并且没有任何东西可以在后续调用中枚举。重申一下,您必须使用 file.seek(0) 重置文件。这也可以在 for...enumerate(file) 语句之前或之后进行。

另一种方法是重新打开文件,但搜索应该有效。

我强烈建议使用 with 语句来自动关闭文件。