Desiigner
Desiigner

Reputation: 2316

How to replace a string with an empty one (in a file)

I have a file with the following text:

  Oh, speak again, bright angel, for thou art
  As glorious to this night, being o'er my head
  As is a winged messenger of heaven
  Unto the white-upturned wondering eyes
  Of mortals that fall back to gaze on him
  When he bestrides the lazy-puffing clouds
  And sales upon the bosom in the air

The task is: I have to replace the lines that begin with "As" with an empty line and then save the output into a new file. So far, I've figured out how to replace the words. Here's my last code:

    def change_strings():
      with open ("file1.txt") as file1:
          strings = file1.readlines()
          for string in strings:
              if not string.startswith("As"):
                  with open("file2.txt", "w") as file2:
                      file2.write(string)

However, I only get the last line saved into a new file. What am I doing wrong?

Upvotes: 0

Views: 244

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46869

this is what i meant in my comment - instead of re-opening and overwriting your output-file open it once only.

also note that there is no need for .readlines(); that will read your whole file in memory which may not be what you want if your file is really big.

from io import StringIO

text = '''Oh, speak again, bright angel, for thou art
As glorious to this night, being o'er my head
As is a winged messenger of heaven
Unto the white-upturned wondering eyes
Of mortals that fall back to gaze on him
When he bestrides the lazy-puffing clouds
And sales upon the bosom in the air
'''

with StringIO(text) as infile, open('out.txt', 'w') as outfile:
    for line in infile:
        if not line.startswith("As"):
            outfile.write(line)

...of course you need to replace StringIO(text) with open('file1.txt', 'r'). this was just to make my example self-containing.

Upvotes: 1

jwg
jwg

Reputation: 5837

You are reopening the same file, truncating it (removing all the contents), and writing a single line into the now empty file, for each step in your loop.

You need to either open the file in append mode ("a" instead of "w") so that each time you append the line to the currently existing contents.

Or, much better, open it once only, outside your loop, and write all the lines you need to it:

def change_strings():
with open ("file1.txt") as file1:
    with open("file2.txt", "w") as file2:
        strings = file1.readlines()
        for string in strings:
            if not string.startswith("As"):
                file2.write(string)

Upvotes: 2

Related Questions