技术求助:如何用Python脚本从列表取值替换模板文件中的SKU文本以批量生成网页
Solution for Batch Generating Web Pages from Template and SKU List
Hey there, I totally get how frustrating it can be when you've spent hours searching for a solution that feels like it should be straightforward—especially when you're still learning the ropes of programming. Let's break this down and get you sorted with a simple Python script that does exactly what you need.
Step-by-Step Approach
Here's the core idea behind the solution:
- Read the entire content of your
websitetemplate.aspfile. - Read each SKU value from
sku_list.txtone by one. - For each SKU, replace the "SKU" string in the template with the actual SKU value.
- Save the modified content as a new ASP file named after the SKU (e.g.,
ABC123.asp).
Python Script Implementation
This script is beginner-friendly and doesn't require any extra libraries—just plain Python that comes with your installation:
# Read the template file content with open('websitetemplate.asp', 'r', encoding='utf-8') as template_file: template_content = template_file.read() # Read each SKU from the list file with open('sku_list.txt', 'r', encoding='utf-8') as sku_file: skus = sku_file.read().splitlines() # Split lines and remove newline characters # Process each SKU and generate the new page for sku in skus: # Skip empty lines in case there are any in the SKU list if not sku.strip(): continue # Replace "SKU" in the template with the current SKU modified_content = template_content.replace("SKU", sku) # Define the output filename (e.g., "ABC123.asp") output_filename = f"{sku.strip()}.asp" # Save the modified content to the new file with open(output_filename, 'w', encoding='utf-8') as output_file: output_file.write(modified_content) print("All pages generated successfully!")
Key Notes to Keep in Mind
- File Paths: Make sure the script is saved in the same folder as
websitetemplate.aspandsku_list.txt, or adjust the file paths in the script to point to their actual locations. - Encoding: Using
encoding='utf-8'ensures that special characters (if any in your template or SKUs) are handled correctly. If you run into encoding issues, you might trylatin-1instead, but utf-8 is the safest default. - Unique "SKU" String: Double-check that the "SKU" in your template only appears in the line you want to replace—if it shows up elsewhere, those will get replaced too. If you need to target a specific line, you could modify the script to only replace the first occurrence, or use a more unique placeholder (like
<!-- SKU_PLACEHOLDER -->) to avoid accidental replacements.
How to Run the Script
- Save the code above into a file named
generate_pages.py. - Open a terminal/command prompt, navigate to the folder where all your files are located.
- Run the command:
python generate_pages.py
That's it—you'll have a new ASP file for every SKU in your list in no time!
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

