Need to replace a string with a file (HTML file) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Need to replace a string with a file (HTML file) (/thread-40632.html) |
Need to replace a string with a file (HTML file) - tester_V - Aug-29-2023 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") exitAny help is appreciated. Thank you RE: Need to replace a string with a file (HTML file) - Larz60+ - Aug-30-2023 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) |