Python 3.x Python3.6:在简单文本文件中循环出现问题,每行都有相同的字符串

Python 3.x Python3.6:在简单文本文件中循环出现问题,每行都有相同的字符串,python-3.x,Python 3.x,python非常新,我在读取一个小文本文件时遇到了一个问题。如您所见,我正在尝试打印一行文本及其索引行号 文本文件如下所示: This is a test ABC This is a test ABC This is a test ABC This is a test ABC This is a test CBA 代码: 问题在于,这会输出: This is a test ABC 0 This is a test ABC 0 This is a test ABC 0 This i

python非常新,我在读取一个小文本文件时遇到了一个问题。如您所见,我正在尝试打印一行文本及其索引行号

文本文件如下所示:

This is a test ABC

This is a test ABC

This is a test ABC

This is a test ABC

This is a test CBA
代码:

问题在于,这会输出:

This is a test ABC
0

This is a test ABC
0

This is a test ABC
0

This is a test ABC
0

This is a test CBA
4

…因此,它似乎将同一行打印4次,而不是单独识别每一行。问题是,对于我正在使用的另一个文件,我希望使用前4行的索引作为文件中其他行的参考点。我知道我在这里很笨,我就是看不到答案

出现缩进错误:程序中的最后一行需要缩进。实际上,python忽略了第行中的
if“test:
并进行打印

更正:

with open ("Loop_test.txt") as f:
    text = f.readlines()
    for row in text:
        if "test" in row:
            print (row, text.index(row))
试着这样做:

    with open("test.txt") as f:
        for i, row in enumerate(f):
            if "test" in row:
                print i, row

对于f中的行:
是一种逐行读取文本文件的python方式。在这里,你需要一个索引,所以我们使用
枚举

是的,很抱歉第一次发布-享受格式化的乐趣。得到了,谢谢,正是我需要的。我还意识到,通过调用text.index(row),python只需匹配它在4行中找到的第一行,并一次又一次地返回该行。Enumerate执行以下任务:)
    with open("test.txt") as f:
        for i, row in enumerate(f):
            if "test" in row:
                print i, row