繁体   English   中英

编辑文件上的数据并将其保存为新文件而不是覆盖它

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

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

using.replace 我可以用我的代码中的变量替换 email 中的这些占位符,以生成显示用户输入变量的消息。

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

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

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

只需在新文件上创建一个模板,阅读该模板,然后单独编写您的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'))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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