By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,454 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 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
  2.  
  3. import os,re
  4.  
  5. fName = r'LOCATION OF FILE'
  6. directory = os.path.dirname(fName)
  7.  
  8. os.chdir(directory)
  9.  
  10. fileName = os.path.basename(fName)
  11. print(fileName)
  12. o_File = open(fileName ,"r+")
  13.  
  14. with o_File as readFile:    
  15.     for searchpattern in readFile:
  16.  
  17.         found_Pattern = re.search("\s*\'[\d]+\==*[\d]*\.*[\d]*\==*[\d]*\.*[\d]*\'*",searchpattern,re.IGNORECASE)
  18.         if found_Pattern:
  19.             found_Pattern_Pat = found_Pattern.group()
  20.             print(value)
  21.             fValue = re.sub(r'==(.+)==','==100==',found_Pattern_Pat)
  22.             print(fValue)
  23.  
  24. o_File.close()
Mar 14 '14 #1
Share this Question
Share on Google+
3 Replies


bvdet
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

bvdet
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.