简体   繁体   中英

Editing data on a file and saving it as a new file instead of overwriting it

I have a file that is an email template written so i can specifically change things based on input the user has given. (Example: a.msg file that reads "Hello! mangName - there seems to be a problem in deptName")

using.replace I am able to replace these placeholders in the email with variables in my code to generate a message displaying the user input variables.

with open('escalation_email.emltpl', 'r+') as f:
  content = f.read()
  f.seek(0)
  f.truncate()
  f.write(content.replace('@@@,,', lineManagerFirstName))
  f.write(content.replace('xxxxx', 'violator'))

However, when I do this, my template is overwritten and changed, so i can't use the.replace again because what's written in the 'placeholder' spots has been changed and overwritten.

Is there a way where I could simply use my orginal.msg file with the 'placeholder text' as a template and save a new file using that template as a base, using its formatting but not overwriting it? So basically - using 'escalation_email.emltpl' as the template - but generating 'new-email.emltpl' as a file with the new data.

Just create a template on a new file, read that one, and write your UserInput.msg separately.

If you don't want to override content make a copy of ir where you do replace the placeholders.

original_content = ''
with open('escalation_email.emltpl', 'r') as f:
  original_content = f.read()
  f.seek(0)
  f.truncate()

content = original_content

with open('userInputFile.msg', 'w') as f:
  f.write(content.replace('@@@,,', lineManagerFirstName))
  f.write(content.replace('xxxxx', 'violator'))

You are writing the changes to the file every time you replace the contents. Remove the f.write . Just replace the contents and use that contents variable to write to a new file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM