Multiple Search And Replace In Python
I need to search in a parent folder all files that are config.xml and in those files replace one string in another. (from this-is to where-as)
Solution 1:
import os
parent_folder_path = 'somepath/parent_folder'for eachFile inos.listdir(parent_folder_path):
if eachFile.endswith('.xml'):
newfilePath = parent_folder_path+'/'+eachFile
file = open(newfilePath, 'r')
xml = file.read()
file.close()
xml = xml.replace('thing to replace', 'with content')
file = open(newfilePath, 'w')
file.write(str(xml))
file.close()
Hope this is what you are looking for.
Solution 2:
You want to take a look at os.walk()
for recursively traveling through a folder and subfolders.
Then, you can read each line (for line in myfile: ...
) and do a replacement (line = line.replace(old, new)
) and save the line back to a temporary file (tmp.write(line)
), and finally copy the temp file over the original.
Post a Comment for "Multiple Search And Replace In Python"