1

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!

marista
  • 25
  • 5
  • 1
    suggest read all into memory, filter lines, then write back. if performance is not problem. – Lei Yang Feb 08 '22 at 13:24
  • Does this answer your question? [Replace and overwrite instead of appending](https://stackoverflow.com/questions/11469228/replace-and-overwrite-instead-of-appending) – Asger Weirsøe Feb 08 '22 at 13:25

1 Answers1

0

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()
marista
  • 25
  • 5