我需要获取文本文件中短语的行号。这句话可能是:
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/