I am new at python, im trying to write a code to print several lines after an if statement.
for example, I have a file "test.txt" with this style:
Hello
how are you?
fine thanks
how old are you?
24
good
how old are you?
i am 26
ok bye.
Hello
how are you?
fine
how old are you?
13
good
how old are you?
i am 34
ok bye.
Hello
how are you?
good
how old are you?
17
good
how old are you?
i am 19
ok bye.
Hello
how are you?
perfect
how old are you?
26
good
how old are you?
i am 21
ok bye.
so I want to print one line after each "how old are you" my code is like this:
fhandle=open('test.txt')
for line in fhandle:
if line.startswith('how old are you?')
print(line) /*** THIS IS THE PROBLEM
I want to print next line after how old are you ( maybe print two lines after "how old are you" )
CodePudding user response:
You can use readlines()
function that returnes lines of a file as a list and use enumerate()
function to loop through list elements:
lines = open('test.txt').readlines()
for i,line in enumerate(lines):
if line.startswith('how old are you?'):
print(lines[i 1], line[i 2])
CodePudding user response:
You could convert the file to a list and use a variable which increases by 1 for each line:
fhandle = list(open('test.txt'))
i = 1
for line in fhandle:
if line.startswith('how old are you?')
print(fhandle[i])
i = 1
CodePudding user response:
Assuming there are always two more lines after each "how old are you", you could just skip to the next iteration by using next(fhandle)
like this:
fhandle = open('test.txt')
for line in fhandle:
if line.startswith('how old are you?'):
print(line)
print(next(fhandle))
print(next(fhandle))
Remember that the for loop just uses fhandle
as an iterator! :)
CodePudding user response:
So as you want to print next line (or two lines) I suggest to use list index. to do that use readlines()
to convert the file to a list
:
fhandle = open('test.txt').readlines()
After you did this you can use len
to calculate list length and index it in a for loop and print next two lines.
for line_index in range(len(fhandle)):
if fhandle[line_index].startswith('how old are you?'):
print(fhandle[line_index 1], fhandle[line_index 2])