簡體   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