mercredi 4 novembre 2015

python code to append after a particular line

I have a configuration file and I want to append a new entry after a specific line. Say my file is: new.conf.1="testing1" new.conf.2="testcode2" new.conf.3="test3"

My python code: (i got from stackflow) import fileinput

def fileappend(filename,searchstr,appendstr):
    for line in fileinput.input(file, inplace=1):
        if searchstr in line:
            line = line.replace(searchstr,searchstr+'\n'+replacestr)

fileappend("filename.txt", "new.conf.3="test3"", "new.conf.4="sample4"

This works to some extent. But I see this is not the optimum way. Can we frame it in a much better way.

Aucun commentaire:

Enregistrer un commentaire