How to grep lines between two patterns in a big file with python

前端 未结 5 1987
青春惊慌失措
青春惊慌失措 2021-01-03 12:45

I have a very big file, like this:

[PATTERN1]
line1
line2
line3 
...
...
[END PATTERN]
[PATTERN2]
line1 
line2
...
...
[END PATTERN]

I need to extract

5条回答
  •  天命终不由人
    2021-01-03 13:00

    I think this does the same thing your code does:

    FILE=open('myfile').readlines()
    
    newfile=[]
    
    pattern = None
    for line in FILE:
        if line[0] == "[" and line[-1] == "]":
            pattern = line[1:-1]
            if pattern == "END PATTERN":
                pattern = None
            continue
        elif pattern is not None and pattern in name_list:
            newfile.append(line)
    

    This way you go through all the lines only once, and fill your list as you go.

提交回复
热议问题