1

I have two files, one is text file and the other is a csv file. The text file has a string format like this

To:      {email}
From:    noreply@deals.com
Subject: Deals!

Hi {first_name},

I want to replace email and first_name with some data I have in the csv file.

I write this code, but I couldn't replace the values

import csv
with open ("emails.csv","r")as csvfile:
    rows = csv.reader(csvfile)

    with open ("email_template.txt","r", encoding="utf8") as efile:
        my_string = efile.read()
        my_string =''.join(i for i in my_string).replace("email","555")
        print(my_string)
        for row in rows:
            print (row[0]+ " " +str(row[2]))
geckos
  • 5,687
  • 1
  • 41
  • 53

1 Answers1

0

Take a look at the following approach:

import csv

with open('email_template.txt') as f_template:
    template = f_template.read()
    
with open('emails.csv') as f_emails:
    csv_emails = csv.DictReader(f_emails)
    
    for row in csv_emails:
        output = template.replace('{email}', row['email']).replace('{first_name}', row['first_name'])
        print(output)
  1. First read the whole template into a template string.
  2. Use a Python DictReader() to read the CSV a line at a time into a row dictionary.
  3. Take the template and replace your two fields with text from the row.
  4. Print the output.

So if your emails.csv file was as follows:

first_name,last_name,email
Fred,Flintstone,ff@bedrock.com
Wilma,Flintstone,wf@bedrock.com

You would get the following output:

To:      ff@bedrock.com
From:    noreply@deals.com
Subject: Deals!

Hi Fred,

To:      wf@bedrock.com
From:    noreply@deals.com
Subject: Deals!

Hi Wilma,
Martin Evans
  • 45,791
  • 17
  • 81
  • 97