[英]Searching and replacing specific string using Python
I'm trying to write a python script that will search and replace specific string in text file 我正在尝试编写一个python脚本来搜索和替换文本文件中的特定字符串
As an example foo.txt is like that: 例如,foo.txt是这样的:
[section1]
option1=xyz
option2=abc
[section2]
option1=aaa
option2=bbb
My objective is to replace only option1 and option2 values under section2 without changing anything in section1 as the following be: 我的目标是仅替换第2节中的option1和option2值,而不更改第1节中的任何内容,如下所示:
[section1]
option1=xyz
option2=abc
[section2]
option1=xxx
option2=zzz
I have tried pysed and many other methods with no dice. 我尝试了pysed和许多其他方法,没有骰子。 Any help from Python Guru ? Python Guru有什么帮助吗?
You may find it easier to use ConfigParser instead of searching and replacing: 您可能会发现使用ConfigParser而不是搜索和替换更为容易:
#!/usr/bin/python
import ConfigParser
import os
config = ConfigParser.ConfigParser()
config.readfp(open('foo.txt'))
config.set("section2", "option1", "xxx1")
config.set("section2", "option2", "yyy1")
# It's always better to write to a temporary file
# and then atomically replace the original:
config.write(open('foo.txt.new', "w"))
os.rename('foo.txt.new', 'foo.txt')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.