Bootstrap FreeKB - Python (Scripting) - Replace lines in a file
Python (Scripting) - Replace lines in a file

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 455fdd in the box below so that we can be sure you are a human.