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
  Replace values in Yaml file with value in dictionary PelleH 1 2,127 Feb-11-2025, 09:51 AM
Last Post: alexjordan
  How to write variable in a python file then import it in another python file? tatahuft 4 903 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 1,038 Dec-19-2024, 11:57 AM
Last Post: snippsat
Question [SOLVED] How to replace characters in a string? Winfried 2 997 Sep-04-2024, 01:41 PM
Last Post: Winfried
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 1,050 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  FileNotFoundError: [Errno 2] No such file or directory although the file exists Arnibandyo 0 900 Aug-12-2024, 09:11 AM
Last Post: Arnibandyo
  "[Errno 2] No such file or directory" (.py file) IbrahimBennani 13 6,271 Jun-17-2024, 12:26 AM
Last Post: AdamHensley
  Matching string from a file tester_V 5 1,807 Mar-05-2024, 05:46 AM
Last Post: Danishhafeez
  file open "file not found error" shanoger 8 6,612 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Replace a text/word in docx file using Python Devan 4 20,828 Oct-17-2023, 06:03 PM
Last Post: Devan

Forum Jump:

User Panel Messages

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