使用python批量读取文件并修改生成新的文件

问题

假设有一个文件,文件里包含一个地址,现在有几十上百个这种地址,这些地址所对应的文件除了地址其他的配置都是相同的,所以,怎么以其中一个文件为模板,替换其中的地址,然后批量生成几十个这种文件呢?

话不多说,直接上代码,十几行代码就可以解决此问题。

def copyAppScanTemplate(target_file, target_url):
    with open("G:\\appScanTemplate\\alpha\\alpha-cloud.scan", 'r') as f_read:
        file_read = f_read.readlines()
        replace_str = "<StartingUrl>https://alpha-cloud.yunshicloud.com/</StartingUrl>"
        for line in file_read:
            with open(target_file, "a+") as f_write:
                if replace_str in line:
                    new_line = line.replace(replace_str, target_url)
                    f_write.write(new_line)
                else:
                    f_write.write(str.encode(line))

def startcp():
    with open("G:\\appScanTemplate\\alpha\\domain.txt", 'r+') as fr:
        file_read = fr.readlines()
        count = 0
        for line in file_read:
            target_url = "<StartingUrl>https://{}/</StartingUrl>" .format(line.strip('\n').strip())
            target_file = "G:\\appScanTemplate\\alpha\\" + line.split('.')[0] + ".scan"
            copyAppScanTemplate(target_file, target_url)
            count += 1
            print(count)

if __name__ == "__main__":
startcp()
domain.txt这个就是存放我们要替换的所有域名,例如:

domain.txt

www.a.com
www.b.com
www.c.com
...
...
...

猜你喜欢

转载自www.cnblogs.com/dogfei/p/12547763.html
今日推荐