Замена текста в одном и том же файле в цикле
Всем привет!
Есть следующая задачка. У меня есть файл, где имеется следующий текст:
`<!-- replace text here-->`
...
`<!-- replace text here-->`
...
`<!-- replace text here-->`
...
`<!-- replace text here-->`
...
`<!-- replace text here-->`
Я хочу с помощью цикла заменить эти значения на следующее:
`<!-- replace text here 0-->`
...
`<!-- replace text here 1-->`
...
`<!-- replace text here 2-->`
...
`<!-- replace text here 3-->`
...
`<!-- replace text here 4-->`
Где цифры - номер цикла. Для этого я написал следующий код:
for r in range (5):
with open(path_to_html, "r+") as f:
contents = f.read()
contents = re.sub(r'<!-- replace text here-->', '<!-- replace text here '+str(r)+'-->', contents)
f.write(contents)
f.truncate()
f.close()
Но по каким-то неведомым мне причинам я получаю следующий результат:
`<!-- replace text here 0-->`
...
`<!-- replace text here 0-->`
...
`<!-- replace text here 0-->`
...
`<!-- replace text here 0-->`
...
`<!-- replace text here 0-->`
Подскажите, пожалуйста, что я делаю не так?