0

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
Morgan Thrapp
10k3 gold badges51 silver badges68 bronze badges
asked Jun 30, 2016 at 16:08
1
  • 2
    Your while loop is inside of your for loop. That while loop runs every time the for loop runs. Commented Jun 30, 2016 at 16:09

2 Answers 2

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()
answered Jun 30, 2016 at 16:57
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Jun 30, 2016 at 16:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.