Python Forum

Full Version: Need to replace a string with a file (HTML file)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
I need to send tons of emails, to do that I have to use an HTML file.
The string “ MessageBody” in the HTML file must be replaced with the Message file which has about 250 words and some coma delimited data that .csv file. I thought I could/should use 'fileinput' but I might be wrong.
Here is a snipped for the task and it does not work, error:
replace() argument 2 must be str, not _io.TextIOWrapper
import fileinput relace_with = open('C:/01/File_replace/Email_Body.txt','r') relace_with.close() with fileinput.FileInput('C:/01/File_replace/Template_EM.html') as file: for line in file: line = line.replace("Message", relace_with) print(line) with open('C:/01/File_replace/Template_EM_New.html','w') as nf : nf.write(f"line\n") exit 
Any help is appreciated.
Thank you
the following assumes the actual text you want to replace is "Message"
wrote on the fly, I have not tested this code

import fileinput with open('C:/01/File_replace/Email_Body.txt','r') as infile: replacement_text = infile.read() with open('C:/01/File_replace/Template_EM.html') as currentfile, open('C:/01/File_replace/Template_EM_New.html','w') as nf: for line in currentfile: if "Message" in line: line.replace("Message", replacement_text) nf.write(line)