There are many threads on find replace text for python but I think my question is different.
I have a bunch of java files with
System.out.println("some text here");
I am trying to write a python script which will replace them all with
if (logger.isInfoEnabled()) {
logger.info("some text here");
}
To do this I have tried:
def findReplace(fileName, sourceText, replaceText):
file = open(fileName, "r") #Opens the file in read-mode
text = file.read() #Reads the file and assigns the value to a variable
file.close() #Closes the file (read session)
file = open(fileName, "w") #Opens the file again, this time in write-mode
file.write(text.replace(sourceText, replaceText)) #replaces all instances of our keyword
# and writes the whole output when done, wiping over the old contents of the file
file.close() #Closes the file (write session)
and pass in:
filename=Myfile.java, sourceText='System.out.println', replaceText='if (logger.isInfoEnabled()) { \n' \logger.info'
However, I am struggling to the get the closing ‘ in the replace. It needs to wrap out around the same output string that is already there. Any tips?
Thanks.
This isn’t perfect — it will only work if the string doesn’t contain any escaped quote marks i.e.
\"— but hopefully it should do the trick.