如何用空的字符串替换字符串(在文件中)

时间:2018-03-01 11:15:53

标签: python

我有一个包含以下文字的文件:

  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

任务是:我必须用空行替换以“As”开头的行,然后将输出保存到新文件中。到目前为止,我已经想出如何替换这些词。 这是我的最后一段代码:

    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)

但是,我只将最后一行保存到新文件中。我做错了什么?

2 个答案:

答案 0 :(得分:2)

您正在重新打开同一个文件,截断它(删除所有内容),并在循环中的每个步骤中将一行写入现在为空的文件。

您需要以附加模式打开文件(" a"而不是" w"),以便每次将该行附加到当前现有内容时。

或者更好的是,只在循环外打开一次,然后写下你需要的所有行:

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)

答案 1 :(得分:1)

这就是我在评论中的意思 - 而不是重新打开并覆盖输出文件只打开一次。

还要注意,.readlines()不需要;这将读取你的整个文件在内存中,如果你的文件非常大,可能不是你想要的。

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)

...当然您需要将StringIO(text)替换为open('file1.txt', 'r')。这只是为了让我的例子自我包含。