简体   繁体   中英

extract specific lines out of file (PYTHON)

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?

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

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM