I'm trying to loop over a .txt file, when I find a keyword, I want to loop over the next 5 rows, but I can't make my loop continue.
This is the text:
11/9/2022 12:37 a. m. - J E. Meta: *Plantilla de contacto*
Respuesta #10002
Nombre: Jesus Meta
Numero Telefonico: 656-199-4322
Monto de Credito: 1200
Numero de Cliente: 127388
Ya tiene su ultimo estacional pagado?: Si
When I find the keyword "Respuesta" I want the loop to continue over the next 5 rows: so I need to get:
Nombre:
Numero:
Monto:
Etc:
This is my code, I'm able to find the keyword! but after finding the keyword, my loop stops and I can't make it continue so that I get the next 5 rows I need to get.
import os
path = os.getcwd() "/prestamos.txt"
with open(path) as file:
data = file.readlines()
for row in data:
if "Respuesta" in row:
print(row)
Thanks!
CodePudding user response:
In the way that you did it:
import os
path = os.getcwd() "/prestamos.txt"
with open(path) as file:
data = iter(file.readlines())
for row in data:
if "Respuesta" in row:
print(row)
# printing the next 5 lines as well:
for _ in range(5):
print(next(data))
Or with some modification and a bit more flexibility:
import os
path = os.getcwd() "/prestamos.txt"
with open(path) as file:
# since `file` is a text file, you can loop directly over it
for line in file:
if 'Respuesta' in line:
next_5 = [next(file) for _ in range(5)]
# now, next_5 is a list of those 5 lines, you can work with it
# the code would continue and find the next block, if you file has multiple
CodePudding user response:
An alternative solution:
import os
path = os.getcwd() "/prestamos.txt"
with open(path) as file:
count = 0
found = false
for row in data:
if 'Respuesta' in data:
found = true
count = 0
if found and count < 5:
print(row)
count = 1
Here I use found
to keep track of when I find "Respuesta"
. Then I use count
to keep track of the number of lines after I find it.