multiple search and replace in python

2019-10-09 02:19发布

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)

2条回答
smile是对你的礼貌
2楼-- · 2019-10-09 02:48

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.

查看更多
聊天终结者
3楼-- · 2019-10-09 02:56
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.

查看更多
登录 后发表回答