替换文件内容中的字符串

123

我怎样才能打开一个名为 Stud.txt 的文件,并将其中的所有出现的 "A" 替换成 "橙色" 呢?


9
请(一如既往地)遵循一般问题指南,说明任何特殊限制,展示你已经尝试过的内容,并询问具体什么让你感到困惑。 - Roger Pate
2
如何使用Python在文件中搜索和替换文本? - jfs
8个回答

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

9
“t”模式只适用于Python 3。此外,您为输出文件提供了上下文管理器,但未关闭输入文件,这似乎不一致。 - Steven Rumbalski
1
但是您正在重命名文件,这样做更糟的是,您正在创建一个新文件。 - user3522371
1
@nakkini 删除旧文件并重命名新文件是这种操作的标准方法,没有任何操作系统支持将文本文件作为可编辑行的流。不过你能想到这种方式还是很有趣的。 - Gareth Davidson

101

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

在此示例中,我使用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:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)
值得一提的是,如果文件名不同,我们可以使用单个with语句更加优雅地完成这项任务。

1
这个解决方案更好,因为与上面的答案不同,你不需要重命名文件。 - user3522371
更好是相对的。如果您不想修改输入文件,另一个答案更好。这取决于使用情况。两者都有帮助。 - László Papp

86
#!/usr/bin/python

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

with open(FileName, "w") as f:
    f.write(newText)

1
我们不能将两个“with”合并成一个吗? - Mehmet Burak Sayıcı
1
@MehmetBurakSayıcı:可能不行,因为我们必须使用“创建/读取/写入/追加”模式之一打开文件。因此,如果我们将其用于读取,没有重新打开的情况下无法写入其中。 - Mark Kahn

22

使用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'))
如果输入和输出文件不同,您需要为read_textwrite_text使用两个不同的变量。
如果您想要更复杂的更改,您将把read_text的结果分配给一个变量,对其进行处理并将新内容保存到另一个变量中,然后再使用write_text保存新内容。
如果您的文件很大,您会更喜欢一种不会在内存中读取整个文件的方法,而是逐行处理它,就像Gareth Davidson在另一个答案中所示(https://dev59.com/L2855IYBdhLWcg3w0H53#4128192),这当然需要使用两个不同的文件作为输入和输出。

write_text 对我无效。它没有更新文件。 - Anurag

11

类似于什么

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

<do stuff with the result>

1
OP提到了“任何出现”,这意味着即使它是一个子字符串,也不适用于您的示例。 - Durdu

10
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)

6
如果您使用的是 Linux,只需将单词 dog 替换为 cat,则可以执行以下操作:

text.txt:

Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!

Linux命令:

sed -i 's/dog/cat/g' test.txt

输出:

Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!

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

在Linux中,您可以使用sed命令来在文件中查找和替换文本。下面是一个示例:

sed -i 's/旧文本/新文本/g' 文件名

这将在指定的文件中查找所有出现的“旧文本”并将其替换为“新文本”。请注意,“g”选项表示全局替换,如果省略该选项,则只会替换每行中第一个匹配项。


-1
最简单的方法是使用正则表达式来完成,假设您想要迭代文件中的每一行(其中存储了'A'),您可以这样做...
import re

input = file('C:\full_path\Stud.txt', 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt', 'w')
for each in saved_input:
    input.write(each)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接