0

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)

3
  • what is the error? Commented Sep 26, 2022 at 19:18
  • Traceback (most recent call last): File "/home/kali/Desktop/replace.py", line 8, in <module> replacements = {'CYBERSCORE':'{}', 'CURRDATE':'{}', 'COLORCODE':'{}'}.format(a, today, color) AttributeError: 'dict' object has no attribute 'format' Commented Sep 26, 2022 at 19:19
  • you can't format dictionaries. use this replacements = {'SCORE':a, 'CURRDATE':today, 'COLORCODE':color} instead of this ` replacements = {'SCORE':'{}', 'CURRDATE':'{}', 'COLORCODE':'{}'}.format(a, today, color)` Commented Sep 26, 2022 at 19:21

1 Answer 1

1

'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}
Sign up to request clarification or add additional context in comments.

2 Comments

Tried that but that is replacing CURRDATE with today what i am trying is to replace CURRDATE with value in today that is 09/27/2022
for date you should use it like this import datetime and today = datetime.date.today().strftime("%m/%d/%Y")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.