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)
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
import os
parent_folder_path = 'somepath/parent_folder'
for eachFile in os.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.
回答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.