-1

I am trying to open a text file and copy lines from "FIRST TEXT" until "LAST TEXT HERE" and write it to another text file. I am not sure how to go about completed this.

with open('SumBillRpt2019-2-27 Cyl 20.txt') as original_file, 
open('test.txt', 'w') as new_file:
    for line in original_file:
        if line.strip() == 'FIRST TEXT HERE' in line.strip():
            new_file.write(original_file.read())
        if line.strip() == 'LAST TEXT HERE':
            new_file.write(original_file.read())
ajburnett344
  • 79
  • 1
  • 9
  • Loop over the lines in `original_file` as you already do. Test for the starting line, set a boolean variable to true when it is found. If this boolean variable is true, write ever line you loop over to the output file, checking for the ending line before you do. When you encounter the ending line, set the boolean variable to false. –  Mar 20 '19 at 16:02

3 Answers3

1

Create a true/false variable that keeps track of whether the current line should be written to the new file, and initialize it to false.

As you're reading each line from the original file, if it matches FIRST TEXT, set the flag to true, otherwise if it matches LAST TEXT, set the flag to false.

Then, if the flag is true, write the line to the new file.

writing = False
with open('original.txt', 'r') as original, open('new.txt', 'w') as new:
    for line in original:
        if line.strip() == 'FIRST TEXT HERE':
            writing = True
        elif line.strip() == 'LAST TEXT HERE':
            writing = False
            # if you know this text will only occur once, you
            # could just break out of the loop here

        if writing:
            new.write(line)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • Great! This worked! I would of never known about the trick of True and False and then using an "IF' statement after an "ELIF" – ajburnett344 Mar 20 '19 at 16:26
0

Use sed:

$ sed -n -e "/FIRST TEXT/,/LAST TEXT HERE/p" < input.txt > output.txt
0

If I understand you correctly, you want to go through the original file, if you find your start string, you start copying to file b, and you stop doing so after reaching your stop string. I would do this with a flag indicating you are in between those two strings:

with open('SumBillRpt2019-2-27 Cyl 20.txt') as original_file,
open('test.txt', 'w') as new_file:
    flag = false
    for line in original_file:
        if line.strip() == 'FIRST TEXT HERE' in line.strip():
            flag = true
        if flag:
            new_file.write(original_file.read())
        if line.strip() == 'LAST TEXT HERE':
            break

Note: I did not test the code.

chefhose
  • 2,399
  • 1
  • 21
  • 32