Search code examples
pythonregexpython-3.xpython-3.5pdf-scraping

How to find a specific line of text in a text file with python?


def match_text(raw_data_file, concentration):
    file = open(raw_data_file, 'r')
    lines = ""
    print("Testing")
    for num, line in enumerate(file.readlines(), 0):
        w = ' WITH A CONCENTRATION IN ' + concentration
        if re.search(w, line):
            for i in range(0, 6):
                lines += linecache.getline(raw_data_file, num+1)
                try:
                    write(lines, "lines.txt")
                    print("Lines Data Created...")
                except:
                    print("Could not print Line Data")
        else:
            print("Didn't Work")

I am trying to open a .txt file and search for a specific string.


Solution

  • Fixed my own issue. The following works to find a specific line and get the lines following the matched line.

    def match_text(raw_data_file, match_this_text):
        w = match_this_text
        lines = ""
        with open(raw_data_file, 'r') as inF:
            for line in inF:
                if w in line:
                    lines += line //Will add the matched text to the lines string
                    for i in range(0, however_many_lines_after_matched_text):
                        lines += next(inF)
                    //do something with 'lines', which is final multiline text
    

    This will return multiple lines plus the matched string that the user wants. I apologize if the question was confusing.