I am trying to read a file, which will break when gets a line starting with "--------------------------" as:
#!/usr/bin/python3
def cinpt():
with open("test", 'r') as finp:
for line in finp:
if line.strip().startswith("start"):
while not line.startswith("---------------"):
sdata = finp.readline()
print(sdata.strip())
cinpt()
a demo input file(test) is:
foo
barr
hii
start
some
unknown
number
of
line
-----------------------------
some
more
scrap
I am expecting the code to break after reading line "line". The expected output is:
some
unknown
number
of
line
it takes start condition properly but not breaking at "----", instead goes to an infinite loop. What I am getting is:
some
scrap
line
-----------------------------
some
more
scrap
2 Answers 2
It loops forever because your line variable does not change during the while loop. You should iterate line by line, its simple.
#!/usr/bin/python3
def cinpt():
with open("test", 'r') as finp:
started = False
for line in finp:
if started:
if line.startswith("---------------"):
break
else:
print(line.strip())
elif line.strip().startswith("start"):
started = True
cinpt()
Comments
You should read the liens form your file in a single place
As it is, you are fetching lines from your file both at for line in finp: line and at sdata = finp.readline() - this likely will be bad for you (as you have found out).
Keep your fiel data in a single place, and use auxiliar state variables to know how you should deal with that data. #!/usr/bin/python3
def cinpt():
with open("test", 'r') as finp:
inside_region_of_interest = False
for line in finp:
if line.strip().startswith("start"):
inside_region_of_interest = True
elif line.startswith("---------------"):
inside_region_of_interest = False
elif inside_region_of_interest:
sdata = line
print(sdata.strip())
cinpt()
That said, your particular problem is that even though your while condition is on the line variable, you never modify that variable inside your while loop. Its content remains fixed at "start\n" up to the end of the file.
whileloop is inside of yourforloop. That while loop runs every time the for loop runs.