如何查找特定文本所在的行号?

时间:2013-08-29 09:55:31

标签: python

这个问题是关于如何找到特定文本的行号,例如“这是我的马”?

文本文件:

this is my name
this is my address
this is my age
this is my horse
this is my book
this is my pc

我的代码:

with open ('test.txt', 'r') as infile:
 ?????

3 个答案:

答案 0 :(得分:2)

使用enumerate函数,因为它适用于任何可迭代的文件(您的文件是)。

for line_number, line in enumerate(infile):
  print line_number, line

答案 1 :(得分:1)

s = "this is my horse"
with open ('test.txt', 'r') as infile:
    print next(index for index, line in enumerate(infile, start=1) if line.strip() == s)

打印4

注意,您需要在行上应用strip()才能在最后删除新行字符。

答案 2 :(得分:1)

您可以这样做:

with open ('test.txt', 'r') as infile:
    data = infile.readlines()
    for line, content in enumerate(data, start=1):
            if content.strip() == 'this is my horse':
                print line

如果您的文件将打印:

4