Python怎么用replace()替换文件中的文本

2024-04-02

你可以使用Python中的replace()方法来替换文件中的文本。以下是一个示例代码,演示如何打开一个文件,读取其中的内容并使用replace()方法来替换指定的文本,然后将修改后的内容写回到文件中:

# 打开文件,读取内容
file_path = 'example.txt'
with open(file_path, 'r') as file:
    content = file.read()

# 使用replace()方法替换文本
old_text = 'apple'
new_text = 'orange'
new_content = content.replace(old_text, new_text)

# 将修改后的内容写回到文件中
with open(file_path, 'w') as file:
    file.write(new_content)

在这个示例中,我们首先打开一个文件example.txt并读取其中的内容。然后使用replace()方法将文本中的apple替换为orange。最后将修改后的内容写回到文件中。你可以根据自己的需求修改old_textnew_text来替换不同的文本。

《Python怎么用replace()替换文件中的文本.doc》

下载本文的Word格式文档,以方便收藏与打印。