python - 获取文件Python中某个短语的行号

标签 python file

我需要获取文本文件中短语的行号。这句话可能是:

the dog barked

我需要打开文件,搜索该短语并打印行号。

我在 Windows XP 上使用 Python 2.6


这就是我所拥有的:

o = open("C:/file.txt")
j = o.read()
if "the dog barked" in j:
     print "Found It"
else:
     print "Couldn't Find It"

这不是家庭作业,它是我正在进行的项目的一部分。我什至不知道如何获取行号。

最佳答案

lookup = 'the dog barked'

with open(filename) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print 'found at line:', num

关于python - 获取文件Python中某个短语的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961265/

相关文章:

python - 求解微分方程时的高频噪声

python - UDP 数据的条件在 PYTHON 中不起作用

python - 图像未存储在数据库 mysql workbench iin python django 中

python - 在类中实例化线程

django文件夹模型

python - Paramiko 等效于管道控件和输入/输出管道

java - 无法在 Java Applet 中将文件设置为可写

java - 为什么我的程序无法读取使用同一程序创建的文件?

Python将redis对象转换为原始数据类型

r - 如何将文件的多行读入数据帧的一行