Removing Multiple Lines after a specific word using Python

Viewed 477

I want to remove the last section of an article (i.e. References section) in a .txt file using Python. By "the whole section" I mean everything after the word "References":

References Section

Is there a way to remove all the content after the word "References" using regex or any other methods?

I have tried the following code, however, it only removes the first line after the word "References":

input_file = open("remove.txt", 'r', encoding= 'utf-8')
prev_line = False
lines =[]
for line in input_file:
    if not prev_line:
        lines.append(line)
    prev_line=False
    if "References" in line:
       prev_line=True
input_file.close()

input_file = open("input.txt", 'w')
for line in lines:
     input_file.write(line)
input_file.close()

Thank you

3 Answers

You need to remove prev_line=False before if "References" in line:, because it will revert the prev_line value to the original False one, and the if not prev_line: lines.append(line) will get executed for all the lines below the line containing References but the one immediately below it.

So, you can use

with open("remove.txt", 'r', encoding= 'utf-8') as input_file:
    prev_line = False
    lines = []
    for line in input_file:
        if not prev_line:
            lines.append(line)
        if "References" in line:
           prev_line=True

with open("input.txt", 'w') as input_file:
    for line in lines:
        input_file.write(line)

Can read in the whole file using read.

text = input_file.read()

find is a string method to locate a substring. We can then use string slicing to select only everything before the desired word, "References" in this case

ans = text[:text.find("References")]

You could also use in-place filtering option of fileinput module:

import fileinput

fin = fileinput.input('remove.txt', inplace=True)
for line in fin:
    if "References" in line:
        fin.close()
    else:
        print(line, end="")
Related