0

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 ?

2
  • you don't need a python guru for that question. you just need to read doc about how to read files. there are needed methods for your question. just search for sectionX and section(X+1) and read and delete option1 and option2, after that replace that options. i finded a tutorial easily, just learn how to use google and don't be afraid of reading. here is the link: pythonforbeginners.com/files/… Commented Jun 14, 2016 at 22:02
  • I would use regex, try looking at the python docs for re Commented Jun 14, 2016 at 22:15

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome ! Worked as expected. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.