-1
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.

Chuck
  • 866
  • 6
  • 17
M. Barbieri
  • 512
  • 2
  • 13
  • 27
  • So where are you stuck? Not sure where you need help – Saleem Mar 14 '16 at 05:16
  • Why don't you add an example and show what works and what doesn't. – roadrunner66 Mar 14 '16 at 05:17
  • well the above example won't enter the if statement, basically, I can't get the if statement to match the pattern I want which is the "w = ' WITH A CONCENTRATION IN...' – M. Barbieri Mar 14 '16 at 05:19
  • 1
    You've got some strange things going on like using `linecache` and whatever that 'write` is supposed to do. Are you just trying to get all lines with `' WITH A CONCENTRATION IN ' + concentration` in it? What is `concentration`? Is it a regex? – tdelaney Mar 14 '16 at 05:21
  • What tdelaney said. What does `linecache.getline` do? Also, what's the `for i in range(0, 6)` loop for? – PM 2Ring Mar 14 '16 at 05:25

2 Answers2

0

If you are simply trying to write all of the lines that hold your string to a file, this will do.

def match_text(raw_data_file, concentration):
    look_for = ' WITH A CONCENTRATION IN ' + concentration
    with open(raw_data_file) as fin, open('lines.txt', 'w') as fout:
        fout.writelines(line for line in fin if look_for in line)
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • This works, thanks. The question was worded badly on my part. I resolved my own problem. There was another step I was looking for. Thank you. – M. Barbieri Mar 14 '16 at 16:50
0

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.

M. Barbieri
  • 512
  • 2
  • 13
  • 27