with open("./Input/Names/invited_names.txt") as f:
names = f.readlines()
with open("./Input/Letters/starting_letter.txt", mode="r+") as f:
letter = f.read()
for name in names:
letter = letter.replace("[name]", name)
f.write(letter)
I am trying to replace the string [name] with actual names stored in a list. The problem is that in all iterations only the first name is replacing the [name] string.
Your question is not very clear, it would be more helpful if you provided the contents of the files.
I think your issue is that when you initilise letter it is stored as a string and when you use the
.replace()method all of the instances are being replaced on the first iteration of the loop. On the next iteration, all of the instances are already replaced so the.replace()method will do nothing.The
.replace()function has an overload where you can specify the maximum amount of occurrences to replace so instead ofletter = letter.replace("[name]", name)you should useletter = letter.replace("[name]", name, 1)