'Overwriting a .txt file in Python
The code below works if the new data is written in a new txt file(test_02.txt).
with open("test_01.txt", "r+") as list_01:
for i in list_01:
if i[0] == "%":
continue
else:
file = []
file.append(i)
with open("test_02.txt", "a") as list_02:
list_02.writelines(file)
The file test_01.txt includes many lines and some of them start with %. I am trying to erase the lines start with % and overwrite the rest in the same txt file(test_01.txt).
How can I do that?
Any help/suggestion would be appreciated. Thanks!
Solution 1:[1]
The code below resolved my problem.
import re
with open("test_01.txt", "r+") as list_01:
data = list_01.read()
list_01.seek(0)
list_01.write(re.sub(r'^%.*\n?', '', data, flags=re.MULTILINE))
list_01.truncate()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | marista |