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!
In the way that you did it:
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)
# 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]
# 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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.