Python (Scripting) - Replace lines in a file

by
Jeremy Canfield |
Updated: July 31 2024
| Python (Scripting) articles
Let's say you have a file named template.txt that contains the following.
Line One
Hello $name
Line Three
Here is how you could create a new file (foo.txt in this example) and replace $name with a value (John Doe in this example).
#!/usr/bin/python3
from string import Template
new_file = open("bar.txt", "w")
with open("template.txt", "r") as file:
for line in file.read().splitlines():
t = Template(line)
adjusted_line = t.substitute({'name': 'John Doe'})
new_file.write(f"{adjusted_line}\n")
new_file.close()
Did you find this article helpful?
If so, consider buying me a coffee over at