Home > Software design >  How to replace string in a file with value of variable using python and save updated content as new
How to replace string in a file with value of variable using python and save updated content as new

Time:09-28

Trying to update string in file with value generated by my code not sure what is the best way to do so.

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)

CodePudding user response:

'dict' object has no attribute 'format' , so replacement is defined incorrectly.

If you change it like this, it will be fine.

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