python - Replace text in a file -


its pretty simple, small code bellow, can read file , match can find musicstyle field , replace value else , write changes on file. xml , know use lxml or other xml parser, want keep using re module because nothing huge, personal database of music collection.

import re  def replace(thefile):     #for iline in (line.rstrip('\n') line in open(thefile,"w")):         if iline.find("musicstyle") >= 0:             mpr = re.search(r'(.*>)(.*?)(<.*)', iline, re.m|re.i)             print mpr.group(2)             # here goes code replace mpr.group(2)              # should use iline.replace('rock','metal') ?  if __name__ == '__main__':     replace('c:\testfile.xml') 

thanks in advance.

use fileinput module if you're trying modify same file:

import fileinput iline in filinput.input(r'c:\testfile.xml',inplace = true):     if iline.find("musicstyle") >= 0:          mpr = re.search(r'(.*>)(.*?)(<.*)', iline, re.m|re.i)          #modify iline here     print iline     #write line  file 

note when you're using windows paths use raw string, otherwise happen:

>>> print 'c:\testfile.xml' c:  estfile.xml            #'\t' converted tab space  >>> print r'c:\testfile.xml'   #raw string works fine c:\testfile.xml 

Comments