By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,748 Members | 1,267 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,748 IT Pros & Developers. It's quick & easy.

search and replace in a text file and save the changes

P: 16
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?
Expand|Select|Wrap|Line Numbers
  1. # !/usr/bin/python
  3. import os,re
  5. fName = r'LOCATION OF FILE'
  6. directory = os.path.dirname(fName)
  8. os.chdir(directory)
  10. fileName = os.path.basename(fName)
  11. print(fileName)
  12. o_File = open(fileName ,"r+")
  14. with o_File as readFile:    
  15.     for searchpattern in readFile:
  17.         found_Pattern ="\s*\'[\d]+\==*[\d]*\.*[\d]*\==*[\d]*\.*[\d]*\'*",searchpattern,re.IGNORECASE)
  18.         if found_Pattern:
  19.             found_Pattern_Pat =
  20.             print(value)
  21.             fValue = re.sub(r'==(.+)==','==100==',found_Pattern_Pat)
  22.             print(fValue)
  24. o_File.close()
Mar 14 '14 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 2.5K+
P: 2,851
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.
Mar 14 '14 #2

P: 16
@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!
Mar 14 '14 #3

Expert Mod 2.5K+
P: 2,851
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.
Mar 14 '14 #4

Post your reply

Sign in to post your reply or Sign up for a free account.