Reputation: 5938
Its pretty simple, with the small code bellow, i can read a file and match where i can find the musicStyle field and replace the value with something else and write the changes on the file. Its a xml and i know that i could use lxml or other xml parser, but i want to keep using the re module because is nothing huge, its for my personal database of music collection.
import re
def replace(theFile):
#for iLine in (line.rstrip('\n') for 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 the code to replace the mpr.group(2)
# should i use iLine.replace('rock','Metal') ?
if __name__ == '__main__':
replace('c:\testfile.xml')
Thanks in advance.
Upvotes: 1
Views: 91
Reputation: 5938
I was able to solve it with:
import re
def replace(theFile):
for line in fileinput.input(theFile,inplace=1):
if line.find("musicStyle") >= 0:
mpr = re.search(r'(.*>)(.*?)(<.*)', line, re.M|re.I)
line = line.replace("rock","metal")
print line,
if __name__ == '__main__':
replace('c:\\testfile.xml')
i had to put a comma on line in order to avoid new lines on the file.
Thanks Ashwini for the direction.
Upvotes: 0
Reputation: 250881
Use the fileinput
module if you're trying to modify the same file:
import fileinput
for 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 the line to the file
Note that when you're using windows paths always use raw string, otherwise this will happen:
>>> print 'c:\testfile.xml'
c: estfile.xml #'\t' converted to tab space
>>> print r'c:\testfile.xml' #raw string works fine
c:\testfile.xml
Upvotes: 2
Reputation: 5143
Honestly, the best thing to do would be to write the output to a separate temporary file, then move the file in place of the original file.
Upvotes: 0