在python3.11中,如何打印一个txt文件,其中f字符串值由csv文件中的数据填充?

eit6fx6z  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(88)

我在课堂上被布置了一个作业,这让我头晕目眩。我们得到了一个txt文件,它是“电子邮件”的模板,其中有两个f字符串值,需要将f字符串值替换为csv文件中的数据并打印到控制台。

To:      {email}
From:    [email protected]
Subject: Deals!

Hi {first_name},

We've got some great deals for you. Check our website!

棘手的部分是,我们不允许将txt文件的内容粘贴为字符串文字,但必须在代码中使用模板。
到目前为止,我只是打印出正确的电子邮件数量有多少数据,但f字符串没有被填写。在这一点上,我已经尝试用多种方法编写这个程序。如果你能帮忙的话,我将不胜感激。

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

import csv

"""This function opens the template, and fills in the f strings with data from the csv file."""
def create_email():

    try:
        a = open("email_template.txt")
        template_mail = a.read()
        with open("emails.csv") as f:
            reader = csv.reader(f, delimiter =',')
            for row in reader:
                email = row[2]
                first_name = row[0]
                print(template_mail)

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

    finally:
        a.close
        
            


create_email()

请注意,我并没有尝试写入txt文件,只是将其内容与csv文件中的数据一起打印到控制台。
我试过使用(template_mail.format(row[2],row[0]))来用csv文件中的值格式化f字符串,但没有成功。我首先创建了一个单独的函数来打开txt文件,该函数在“create_email”函数内部调用。结果与我提供的代码相同。我需要的控制台打印出的模板提供了f字符串填充数据从提供的csv文件。我期望我的解决方案能做到这一点,从所有的挖掘我已经做了网上,但没有任何工作。

ktca8awb

ktca8awb1#

让我们从模板开始:

To:      {email}
From:    [email protected]
Subject: Deals!

Hi {first_name},

We've got some great deals for you. Check our website!

一个小的CSV文件:

Bill,Gates,[email protected]
John,Doe,[email protected]

然后

from pathlib import Path
import csv

BASE = Path('/Volumes/G-Drive')

with open(BASE.joinpath('email_template.txt')) as template:
    ts = template.read()
    with open(BASE.joinpath('emails.csv')) as emails:
        for first_name, _, email in csv.reader(emails):
            print(ts.format(email=email, first_name=first_name))

输出:

To:      [email protected]
From:    [email protected]
Subject: Deals!

Hi Bill,

We've got some great deals for you. Check our website!

To:      [email protected]
From:    [email protected]
Subject: Deals!

Hi John,

We've got some great deals for you. Check our website!

相关问题