当前位置: 代码迷 >> python >> 搜索和更改文本文件中的字符串(PYTHON)
  详细解决方案

搜索和更改文本文件中的字符串(PYTHON)

热度:70   发布时间:2023-07-16 10:08:35.0

我在互联网上搜索了很多东西,却没有找到合适的代码来搜索某个文本文件中的字符串并将其替换为其他单词?

非常感谢您的帮助。并感谢您的帮手!!

假设文本文件的名称是fruits ,并且具有以下内容:

watermelon
banana
apple orange

我想在字符串"grapes"替换字符串"orange" "grapes"

首先使用内置的打开文件以进行读写。

然后阅读所有内容,并使用将orange替换为grapes

现在,使用将偏移量设置为0 ,因为您要覆盖内容。 之后,将结果写入文件。

myfile = 'fruits.txt' # Replace this with the path to your file

with open(myfile, 'r+') as f:
    contents = f.read()
    result = contents.replace('orange', 'grapes')
    f.seek(0)
    f.write(result)

用法示例:

$ echo -e "watermelon\nbanana\napple orange" > fruits.txt
$ python test.py
$ cat fruits.txt
watermelon
banana
apple grapes