替换文件内容中的字符串

Joe*_*oey 87 python string file-io

如何打开文件Stud.txt,然后用"Orange"替换"A"的任何出现?

Gar*_*son 170

with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))
Run Code Online (Sandbox Code Playgroud)

  • "给出家庭作业问题的答案"是一个非常愚蠢的评论.如果有人想要帮助,那就帮助他们.不是每个人都想要做他们的硬件,有些人真的想学点东西...... (20认同)
  • 文本模式的"t"仅为Python 3.此外,您为输出文件提供了上下文管理器,但无法关闭输入文件,这似乎不一致. (8认同)
  • 我确实需要这个来做家庭作业,它极大地帮助了我 (5认同)
  • @mikeybeck CoVID 措施已将我所有的工作变成了家庭作业。这个答案仍然有帮助。 (5认同)

Ada*_*tan 71

如果您想要替换同一文件中的字符串,您可能必须将其内容读入本地变量,关闭它并重新打开它以进行写入:

我在这个例子中使用了with语句,它在with块终止后关闭文件- 通常是在最后一个命令完成执行时,或者是异常.

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        s = f.read()
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)
Run Code Online (Sandbox Code Playgroud)

值得一提的是,如果文件名不同,我们可以通过单个with语句更优雅地完成此操作.


Mar*_*ahn 37

  #!/usr/bin/python

  with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

  with open(FileName, "w") as f:
    f.write(newText)
Run Code Online (Sandbox Code Playgroud)

  • 简明扼要,最佳答案 IMO (6认同)

Tar*_*ama 9

就像是

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>
Run Code Online (Sandbox Code Playgroud)


Jor*_*eda 7

使用 pathlib ( https://docs.python.org/3/library/pathlib.html )

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))
Run Code Online (Sandbox Code Playgroud)

如果输入和输出文件不同,您可以为read_text和使用两个不同的变量write_text

如果您想要一个比单个替换更复杂的更改,您可以将 的结果分配read_text给一个变量,对其进行处理并将新内容保存到另一个变量中,然后使用write_text.

如果您的文件很大,您会更喜欢一种不读取内存中整个文件的方法,而是逐行处理它,如 Gareth Davidson 在另一个答案中所示(/sf/answers/288973471/) ,这当然需要使用两个不同的文件进行输入和输出。


Fal*_*rri 6

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)
Run Code Online (Sandbox Code Playgroud)


use*_*754 6

如果您使用的是Linux,并且只想替换单词dog,则cat可以执行以下操作:

text.txt:

Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Run Code Online (Sandbox Code Playgroud)

Linux命令:

sed -i 's/dog/cat/g' test.txt
Run Code Online (Sandbox Code Playgroud)

输出:

Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
Run Code Online (Sandbox Code Playgroud)

原始帖子:https : //askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands