【问题标题】:Editing data on a file and saving it as a new file instead of overwriting it编辑文件上的数据并将其保存为新文件而不是覆盖它
【发布时间】:2021-08-28 01:29:41
【问题描述】:

我有一个编写的电子邮件模板文件,因此我可以根据用户给出的输入专门更改内容。 (例如:一个 .msg 文件,内容为“Hello!mangName - deptName 中似乎有问题”)

使用 .replace 我可以将电子邮件中的这些占位符替换为我的代码中的变量,以生成显示用户输入变量的消息。

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'))

但是,当我这样做时,我的模板被覆盖和更改,因此我不能再次使用 .replace,因为“占位符”位置中写入的内容已被更改和覆盖。

有没有一种方法可以让我简单地使用带有“占位符文本”的原始 .msg 文件作为模板,并使用该模板作为基础保存一个新文件,使用其格式但不覆盖它? 所以基本上 - 使用 'escalation_email.emltpl' 作为模板 - 但生成 'new-email.emltpl' 作为包含新数据的文件。

【问题讨论】:

    标签: python python-3.x email replace overwrite


    【解决方案1】:

    每次替换内容时,您都会将更改写入文件。删除f.write。只需替换内容并使用该内容变量写入新文件

    【讨论】:

      【解决方案2】:

      只需在新文件上创建一个模板,阅读该模板,然后分别写下您的UserInput.msg

      如果您不想覆盖 content,请复制 ir 以替换占位符。

      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'))
      
      

      【讨论】:

      • 您也可以像with open(template_file) as template, open(new_file,’w’) as new_file:一样打开文件(模板和新文件)
      猜你喜欢
      • 2019-10-10
      • 2021-03-13
      • 2018-02-18
      • 2020-07-27
      • 1970-01-01
      • 2019-06-04
      • 2018-08-22
      • 2019-02-28
      • 2021-06-01
      相关资源
      最近更新 更多