I have a text file where most of the text is boilerplate, with around two dozen variables that I'm changing in Python depending on the room that the file pertains to. Which method of replacing the text is "better", wrapping the entire text file into one big triple quoted f'string', or stacking up a bunch of .replace() ?
The file isn't very big and there's only about 300 rooms, so in my case milliseconds don't really matter. I'm thinking that for readability and future edits the .replace() way would be better, but I don't want to create a bad habit if doing it that way is a bad idea. Thanks in advance for any help.
simplified pseudo code:
class Thing:
def __init__(self, name, var1, var2, var3):
self.name = name
self.var1 = var1
self.var2 = var2
self.var3 = var3
def doing_it_the_replace_way(thing):
with open('template.txt', 'r') as file:
file_data = file.read()
file_data = file_data.replace('placeholder_name', 'name')
file_data = file_data.replace('placeholder1', 'var1')
file_data = file_data.replace('placeholder2', 'var2')
file_data = file_data.replace('placeholder3', 'var3') # etc.
with open('output file.txt', 'w') as file:
file.write(file_data)
def doing_it_the_f_string_way(thing):
file_data = f"""This is the entire template text from {thing.var1} about the time I got a
{thing.var2} stuck in my {thing.var3} at band camp."""
with open('output file.txt', 'w') as file:
file.write(file_data)