Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a string and insert text after it in Python

Tags:

python

I am still learner in python. I was not able to find a specific string and insert multiple strings after that string in python. I want to search the line in the file and insert the content of write function

I have tried the following which is inserting at the end of the file.

line = '<abc hij kdkd>'
dataFile = open('C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml', 'a')
dataFile.write('<!--Delivery Date: 02/15/2013-->\n<!--XML Script: 1.0.0.1-->\n')
dataFile.close()
like image 557
Mallik Avatar asked Dec 20 '13 11:12

Mallik


1 Answers

You can use fileinput to modify the same file inplace and re to search for particular pattern

import fileinput,re  

def  modify_file(file_name,pattern,value=""):  
    fh=fileinput.input(file_name,inplace=True)  
    for line in fh:  
        replacement=value + line  
        line=re.sub(pattern,replacement,line)  
        sys.stdout.write(line)  
    fh.close()  

You can call this function something like this:

modify_file("C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml",
            "abc..",
            "!--Delivery Date:")
like image 126
s02 Avatar answered Oct 11 '22 00:10

s02