简体   繁体   中英

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

As an example foo.txt is like that:

[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:

[section1]
option1=xyz
option2=abc

[section2]
option1=xxx
option2=zzz

I have tried pysed and many other methods with no dice. Any help from Python Guru ?

You may find it easier to use ConfigParser instead of searching and replacing:

#!/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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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