[英]Searching and changing a string in text file (PYTHON)
I searched a lot in the internet and I didn't find an appropriate code that searches for a string in a certain text file and replaces it with a different word? 我在互联网上搜索了很多东西,却没有找到合适的代码来搜索某个文本文件中的字符串并将其替换为其他单词?
Would appreciate help.. And thanks for the helpers!! 非常感谢您的帮助。并感谢您的帮手!!
Let's say that the name of the text file is fruits
and it has the following contents: 假设文本文件的名称是
fruits
,并且具有以下内容:
watermelon
banana
apple orange
And I want to replace the string "orange"
in the string "grapes"
我想在字符串
"grapes"
替换字符串"orange"
"grapes"
First open the file for reading and writing using the built-in open function . 首先使用内置的打开功能打开文件以进行读写。
Then read all its contents and replace orange
with grapes
using str.replace . 然后阅读所有内容,并使用str.replace将
orange
替换为grapes
。
Now set the offset to 0
with the seek-method because you want to override the contents. 现在,使用查找方法将偏移量设置为
0
,因为您要覆盖内容。 After that write the result to the file. 之后,将结果写入文件。
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)
Example usage: 用法示例:
$ echo -e "watermelon\nbanana\napple orange" > fruits.txt
$ python test.py
$ cat fruits.txt
watermelon
banana
apple grapes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.