8

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()
3
  • 4
    This code is a bit confusing. First, you set variable line to some text (<abc..), only to never use it again. Then you open file for appending (a parameter), write some text into it (<!--Deliv..) and you close the file. What exactly were you trying to accomplish? Commented Dec 20, 2013 at 11:03
  • actually i have tried some if statements for searching the text in a file and insert the text after that lines once it is fetched.but i did nt get the proper result Commented Dec 20, 2013 at 11:08
  • I want to insert the text "<delive..." after "<abc hij .." to a file once i find the text. Commented Dec 20, 2013 at 11:15

4 Answers 4

4

Python strings are immutable, which means that you wouldn't actually modify the input string -you would create a new one which has the first part of the input string, then the text you want to insert, then the rest of the input string.

You can use the find method on Python strings to locate the text you're looking for:

def insertAfter(haystack, needle, newText):
  """ Inserts 'newText' into 'haystack' right after 'needle'. """
  i = haystack.find(needle)
  return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]

You could use it like

print insertAfter("Hello World", "lo", " beautiful") # prints 'Hello beautiful world'
Sign up to request clarification or add additional context in comments.

3 Comments

what is an haystack do i need to declare or initialize something?
This is an haystack and this is a needle :). Haystack represents your file content and needle the line you search. newText is what you want to insert. To use that, you have to load the whole content of the file in memory with f.read(), do the replacement and write the whole content back (reopen the file in write mode).
by running this code it saying haystack is not defined so that is the error i am getting
3

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:")

Comments

1

Here is a suggestion to deal with files, I suppose the pattern you search is a whole line (there is nothing more on the line than the pattern and the pattern fits on one line).

line = ... # What to match
input_filepath = ... # input full path
output_filepath = ... # output full path (must be different than input)
with open(input_filepath, "r", encoding=encoding) as fin \
     open(output_filepath, "w", encoding=encoding) as fout:
    pattern_found = False
    for theline in fin:
        # Write input to output unmodified
        fout.write(theline)
        # if you want to get rid of spaces
        theline = theline.strip()
        # Find the matching pattern
        if pattern_found is False and theline == line:
            # Insert extra data in output file
            fout.write(all_data_to_insert)
            pattern_found = True
    # Final check
    if pattern_found is False:
        raise RuntimeError("No data was inserted because line was not found")

This code is for Python 3, some modifications may be needed for Python 2, especially the with statement (see contextlib.nested. If your pattern fits in one line but is not the entire line, you may use "theline in line" instead of "theline == line". If your pattern can spread on more than one line, you need a stronger algorithm. :)

To write to the same file, you can write to another file and then move the output file over the input file. I didn't plan to release this code, but I was in the same situation some days ago. So here is a class that insert content in a file between two tags and support writing on the input file: https://gist.github.com/Cilyan/8053594

1 Comment

If i want to write the output to the same file ?
0

Frerich Raabe...it worked perfectly for me...good one...thanks!!!

        def insertAfter(haystack, needle, newText):
            #""" Inserts 'newText' into 'haystack' right after 'needle'. """
            i = haystack.find(needle)
            return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]


        with open(sddraft) as f1:   
            tf = open("<path to your file>", 'a+')
            # Read Lines in the file and replace the required content
            for line in f1.readlines():
                build = insertAfter(line, "<string to find in your file>", "<new value to be inserted after the string is found in your file>") # inserts value
                tf.write(build)
            tf.close()
            f1.close()
            shutil.copy("<path to the source file --> tf>", "<path to the destination where tf needs to be copied with the file name>")

Hope this helps someone:)

2 Comments

What is "shutil"?
How to you call the function, similar to @Frerich? What is "sddraft"?

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.