繁体   English   中英

使用Python搜索和替换特定字符串

[英]Searching and replacing specific string using Python

我正在尝试编写一个python脚本来搜索和替换文本文件中的特定字符串

例如,foo.txt是这样的:

[section1]
option1=xyz
option2=abc

[section2]
option1=aaa
option2=bbb

我的目标是仅替换第2节中的option1和option2值,而不更改第1节中的任何内容,如下所示:

[section1]
option1=xyz
option2=abc

[section2]
option1=xxx
option2=zzz

我尝试了pysed和许多其他方法,没有骰子。 Python Guru有什么帮助吗?

您可能会发现使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM