user3754136
user3754136

Reputation: 529

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

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)

Upvotes: 0

Views: 107

Answers (1)

Hakan Müştak
Hakan Müştak

Reputation: 26

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

Upvotes: 1

Related Questions