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:    [email protected]
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]))
5
  • 1
    Hi and welcome! Why not using some punctuation marks? Commented Jun 18, 2022 at 4:10
  • 1
    it's first time for me to use this website, I don't know how to use it actually, I need help for solving my code Commented Jun 18, 2022 at 4:19
  • You need to share some demo data for the CSV as the answer depends on it
    – geckos
    Commented Jun 18, 2022 at 4:54
  • Where did the "555" come from?
    – Lazyer
    Commented Jun 18, 2022 at 9:05
  • Try looking at How to replace string character pattern using Python in csv file. Commented Jun 18, 2022 at 22:16

1 Answer 1

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,[email protected]
Wilma,Flintstone,[email protected]

You would get the following output:

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

Hi Fred,

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

Hi Wilma,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.