You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python3.11读取CSV数据填充TXT模板F-string并打印?

解决方法

你的问题核心是模板里的命名占位符和你使用format的方式不匹配,同时直接读取的字符串不会自动作为f-string解析。下面是具体修复方案:

问题分析

  1. 模板中的{email}和{first_name}是命名占位符,你之前用template_mail.format(row[2], row[0])传递的是位置参数,两者不匹配,所以无法完成替换。
  2. 从文件读取的字符串是普通字符串,不能直接当作f-string使用——f-string是代码层面的语法糖,无法在运行时直接解析外部读取的字符串。

修复后的代码

"""This program reads an email template and csv file,
with names and generates emails based on these files."""

import csv

def create_email():
    try:
        # 用with语句自动管理模板文件,无需手动执行close操作
        with open("email_template.txt", "r") as template_file:
            template_mail = template_file.read()
        
        with open("emails.csv", "r") as csv_file:
            reader = csv.reader(csv_file, delimiter=',')
            # 如果CSV文件第一行是表头(比如"first_name,xxx,email"),取消下面注释跳过表头
            # next(reader)
            for row in reader:
                email = row[2]
                first_name = row[0]
                # 使用format的关键字参数匹配模板中的命名占位符
                filled_email = template_mail.format(email=email, first_name=first_name)
                print(filled_email)
                # 打印分隔线区分不同邮件(可选)
                print("-" * 50)

    except Exception as e:
        print("Error: ", e)

create_email()

关键改动说明

  • 模板文件优化:改用with语句打开模板文件,自动处理文件关闭,解决原代码中a.close缺少括号(未执行关闭操作)的问题。
  • format用法修正:使用format(email=email, first_name=first_name)的关键字参数形式,和模板中的{email}、{first_name}一一对应,确保占位符被正确替换。
  • 表头处理:如果你的CSV文件包含表头行,记得取消next(reader)的注释,避免把表头当作数据处理。

替代方案:使用string.Template

如果你不想用format,也可以用Python的string.Template类,需要先把模板中的占位符改成$email和$first_name,代码示例如下:

import csv
from string import Template

def create_email():
    try:
        with open("email_template.txt", "r") as template_file:
            template_mail = Template(template_file.read())
        
        with open("emails.csv", "r") as csv_file:
            reader = csv.reader(csv_file, delimiter=',')
            for row in reader:
                filled_email = template_mail.substitute(email=row[2], first_name=row[0])
                print(filled_email)
                print("-" * 50)

    except Exception as e:
        print("Error: ", e)

create_email()

这种方式的好处是占位符语法更独立,不会和模板中其他含大括号的内容冲突,但需要同步修改模板文件的占位符格式。

内容的提问来源于stack exchange,提问作者AnthonyAtHome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:54:52