search and replace in a text file and save the changes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nischalinn
    New Member
    • Mar 2014
    • 16

    search and replace in a text file and save the changes

    I am trying to search for a pattern in a text file and replace with another string.
    I've opened the file in "r+" mode and used re.sub for replacement text.

    The python output window is showing the desired result, but when I open the text file there is no change. The string that is to be replaced is not replaced in the text file.

    Why is it so?
    Code:
    # !/usr/bin/python
    
    import os,re
    
    fName = r'LOCATION OF FILE'
    directory = os.path.dirname(fName)
    
    os.chdir(directory)
    
    fileName = os.path.basename(fName)
    print(fileName)
    o_File = open(fileName ,"r+")
    
    with o_File as readFile:    
        for searchpattern in readFile:
            
            found_Pattern = re.search("\s*\'[\d]+\==*[\d]*\.*[\d]*\==*[\d]*\.*[\d]*\'*",searchpattern,re.IGNORECASE)
            if found_Pattern:
                found_Pattern_Pat = found_Pattern.group()
                print(value)
                fValue = re.sub(r'==(.+)==','==100==',found_Pattern_Pat)
                print(fValue)
                       
    o_File.close()
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Assuming your data file is not so large it cannot be stored in memory, compile a list of modified and unmodified lines of text (searchpattern would be one line of text). After closing o_File, open the file again or another suitable file in write mode and write the contents of the compiled list to it. Close the file object to flush the contents to disk.

    Comment

    • nischalinn
      New Member
      • Mar 2014
      • 16

      #3
      @BVDET Thank you for the prompt reply.
      Please can you tell me why I've to do so? In the tutorials, it is said that when you open a file in "r+" mode, the file is accessed in read as well as write mode.
      But in my case, why it is not happening?
      Please can you clarify me.

      Thank You!

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        OK, "r+" instead of "r" is for reading and writing, but you still have to write the updated text out to the file. It may work on a line by line basis - I'm not sure. Let us know how it turns out.

        Comment

        Working...