E
E
enwr2020-09-17 23:37:39
Python
enwr, 2020-09-17 23:37:39

How can I find out which line the given word is on?

text = open('text.txt', 'r') a
= text.read()
d = str(a)
if 'word' in d:
bottom line
text.close()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Yakushenko, 2020-09-18
@enwr

for index, line in enumerate(open('text.txt', 'r'), start=1):
    if 'word' in line:
        print(index, line.strip())
        break

D
dmshar, 2020-09-18
@dmshar

text= open('text.txt', 'r')
line = text.readline()
i=0
while line:
    print (line),
    if line=='word':
        ns=i
        break
    line = text.readline()
    i+=1
text.close()
print ('Номер нужной строки ',ns)

Or even so
text= open('text.txt', 'r')
for id, line in enumerate(text.readlines()):
    print (line)
    if line=='word':
        break
text.close()
print ('Номер нужной строки ',id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question