Adam
Adam

Reputation: 35

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.

Upvotes: 2

Views: 5168

Answers (1)

Lukas Schmid
Lukas Schmid

Reputation: 1960

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.

Upvotes: 3

Related Questions