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!
Code that worked for me
I ended up sticking to a different loop with while:
This is the code that worked for me in case it helps someone else:
import os
import pandas as pd
path = os.getcwd() + "/prestamos.txt"
ls = {}
with open(path) as file:
data = file.readlines()
n = 0
while n <= len(data)-1:
if "Respuesta" in data[n]:
r = range(n,n+6)
for row in r:
#print(row,data[row])
col,actual_data = data[row].strip().split(":")
#print(col,actual_data)
if col not in ls:
ls.update({col:[actual_data]})
elif col in ls:
ls[col].append(actual_data)
n += 1
df = pd.DataFrame(ls)
print(df.head())
thank you!