简体   繁体   中英

Python Script to Replace text in template file with value from a list

This is probobly a blink of an eye to most of you but I am learning.

I am editing multiple web pages and want to edit one line at the top and insert a value into it with an item in a list.

Then move onto the next item in the list and edit the template file with this item and move onto the next one. I have read for a few hours on here now but cannot find a solution. Please can someone help.

Currently have a file structure of: websitetemplate.asp (there is a line at the top with "SKU" in it which is the portion to edit. sku_list.txt (this has multiple values which I want to insert into the template and save each one.

Here's a quick python solution:

with open('sku_list.txt', 'r') as skusfile:
    for sku in skusfile.read().split('\n'):
        with open("websitetemplate.asp", 'r') as templatefile:
            template = templatefile.read()
        with open(f"{sku}.asp", 'w+') as writefile:
            writefile.write(template.replace('[replacekeyword]', sku))

It opens your list and splits it by newlines (insert whatever operator you have inbetween).

Then it opens the website template and saves it in the template variable.

Last, you replace whatever replacekeyword you have with the different values in the skulist and write them each to their own file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM