Reputation: 195
I have text like this
ABC
DEF
Ref.By
AAA
AAA
I want remove all the line before the line Ref.By.
How can I do it in python ?
Upvotes: 1
Views: 1730
Reputation: 402844
lines = open('your_file.txt', 'r').readlines()
search = 'Ref.By'
for i, line in enumerate(lines):
if search in line:
break
if i < len(lines) - 1:
with open('your_file.txt', 'w') as f:
f.write('\n'.join(lines[i + 1:]))
This is alright provided your file size is well within 2-4 MB. It becomes problematic to store it in memory beyond that point.
Upvotes: 0
Reputation: 1258
Try this
text_str = """ABC
DEF
Ref.By
AAA
AAA"""
text_lines = text_str.split("\n")
idx = text_lines.index("Ref.By") + 1
result_text = "\n".join(text_lines[idx:])
print(result_text)
Upvotes: 1