簡體   English   中英

如何使用 python 將文件中的字符串替換為變量值並將更新的內容保存為新文件

[英]How to replace string in a file with value of variable using python and save updated content as new file

嘗試使用我的代碼生成的值更新文件中的字符串,但不確定最好的方法是什么。

from datetime import datetime

import sys
import time
today = datetime.today().strftime('%m/%d/%Y')
a = 546
color = "#F1C40F"
replacements = {'SCORE':'{}', 'CURRDATE':'{}', 'COLORCODE':'{}'}.format(a, today, color)

with open('/home/kali/Desktop/template.txt') as infile, open('/home/kali/Desktop/updatedtemplate.txt', 'w') as outfile:
    for line in infile:
        for src, target in replacements.items():
            line = line.replace(src, target)
        outfile.write(line)

' dict ' object沒有屬性' format ',所以替換定義不正確。

如果你像這樣改變它,那就沒問題了。

replacements = {'SCORE': a, 'CURRDATE': today, 'COLORCODE': color}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM