問題
假設有一個文件,文件里包含一個地址,現在有幾十上百個這種地址,這些地址所對應的文件除了地址其他的配置都是相同的,所以,怎么以其中一個文件為模板,替換其中的地址,然后批量生成幾十個這種文件呢?
話不多說,直接上代碼,十幾行代碼就可以解決此問題。
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
...
...
...