How would I remove all lines in a text file after a specific line?
For example, I want to change the file:
This is important line one.
This is important line two.
Here begins the throw away lines.
Here is throw away line one.
And this is throw away line two.
To this:
This is important line one.
This is important line two.
I think I would want to regex match r'Here begins the (.|\n)*' to match everything in the file after 'Here begins the', but then I'm lost.
I tried this but it's not working:
import re
with open ("file1.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
found_line = re.search(r'^Here begins the(.|\n)*',lines)
lines = lines[:found_line.start()]
with open ("file1.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
Thank you.
You can read the file, apply the regex you mentioned with re.sub() and write to the file like this:
import re
with open("file.txt", "r") as f:
data = f.read()
subbed_data = re.sub(r'Here begins the throw away lines.(.|\n)*', "", data)
with open("file.txt", "w") as f:
f.writelines(subbed_data)
Output:
This is important line one.
This is important line two.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments