简体   繁体   中英

Removing lines above specific line in text in python

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM