Python Forum
Need to replace a string with a file (HTML file)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need to replace a string with a file (HTML file)
#1
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
Reply
#2
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)
tester_V likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching string from a file tester_V 5 453 Mar-05-2024, 05:46 AM
Last Post: Danishhafeez
  file open "file not found error" shanoger 8 1,158 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Replace a text/word in docx file using Python Devan 4 3,467 Oct-17-2023, 06:03 PM
Last Post: Devan
  How can I change the uuid name of a file to his original file? MaddoxMB 2 945 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  why doesn't it replace all html tags? Melcu54 3 762 Jul-05-2023, 04:47 AM
Last Post: Melcu54
  splitting file into multiple files by searching for string AlphaInc 2 908 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Formatting a date time string read from a csv file DosAtPython 5 1,300 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  '' FTP '' File upload with a specified string and rename midomarc 1 1,175 Apr-17-2023, 03:04 AM
Last Post: bowlofred
  Replace string in a nested Dictianory. SpongeB0B 2 1,217 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,116 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020