简体   繁体   中英

How to extract line after line till a specific keyword and then declare to a variable

I'm currently trying to extract some lines till i reach a keyword out of a .txt file to declare a variable with the text. Right now I have this code to get the lines I want to have:

def extract_line(row): 
    a = open("Z:/xyz/xyz/test.txt","r", encoding="utf-8")
    b = a.readlines()
    a.close()
    count = 0
    for line in b:
        count += 1
        if count == row:
            if "REQUIREMENT TYPE " in line:
                break
            else:
                print(line)
                extract_line(row + 1)

which works fine for printing out the lines, but I can't extract the lines to declare a variable with the text. How do I do that?

I'm not sure why you are calling the function recursively.

If I got your question right, you want to store the lines you get until you hit a certain keyword. Once you hit the keyword, you want to break and you need a variable to have the lines you have read until that point.

You can do this with the following code:

with open("file.txt", "r") as f:
    extracted_line = []         # create an empty list to store the extracted lines
    for line in f:
        if 'REQUIREMENT TYPE' in line: # if keyword is present in the current line, break
            break
        else:
            extracted_line.append(line) # else, append the line to store them later
    stored_lines = ''.join(extracted_line) # variable which stores the lines till keyword
    print stored_lines

f.close()

I have put comments beside the code. Hope this answers your question. Let me know if you need any clarification.

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