Reputation: 31
i have a big problems in extracting lines out of a text file: My text file ist built like the following:
BO_ 560 VR_Sgn_1: ALMN
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
BO _ 561 VSet_Current : ACM
SG_2_ Vr_set
SG_3 Dars
BO_ 4321 CDSet_tr : APL
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
SG_1_ Vr_1
SG_2_ Vr_set
SG_3 Dars
....
The textfile includes about 1000 of these "BO_ " Blocks...
i would like to have the expressions between the "BO_ "s. Here my previous code:
show_line= False
with open("test.txt") as f:
for line in f:
if line.startswith("BO_ 560"):
show_line=True
elif line.startswith("\n")
show_line= False
if show_line and not line.startswith("BO_ 560")
print line
in this case i would like to expect the following output:
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
Can anyone help me?
Upvotes: 0
Views: 68
Reputation: 405
I think there's problem with:
elif line.startswith("\n")
You want to wait for next "BO_" instead of EOL to disable show_line, try this:
show_line = False
with open("test.txt") as f:
for line in f:
if line.startswith("BO_ 560"):
show_line = True
elif line.startswith("BO_"):
show_line = False
elif show_line:
print line
Upvotes: 1
Reputation: 1957
If what you want is to output all the blocks between "BO's" you can do something like this:
with open("test.txt") as f:
for line in f:
if line.startswith("BO"):
print ""
else:
print line
Upvotes: 0
Reputation: 1856
You need to skip further processing of the line when you see BO_ or BO _
I am not sure if you only want for first block or all.
Does below option solve your problem.
show_line = False
with open("test.txt") as f:
for line in f:
line = line.strip("\n")
if line.startswith("BO_ ") or line.startswith("BO _ "):
show_line = False if show_line else True
continue
if show_line:
print line
Upvotes: 0