Additional carriage return created when writing mako rendered template to a file

400 Views Asked by At

I am using the mako template library to generate a test.txt file, but the generated file contains additional empty lines in between each row.

I have found a similar question about this issue here and the solution proposed suggests the use of markupsafe, but I am not convinced that this is also suitable in my case as it considers passing the text to be formatted as an argument when rendering the template, which is not what I want to do (I don't want to change most of the text in the template, just a few variables I am inputting).

I think it's also worth mentioning that if I print the rendered template in Python, it prints with the correct formatting; the extra lines only appear in the file I write the template data to (test.txt) using Python's file write().

1

There are 1 best solutions below

0
phantom-99w On

Piggy-backing off of this answer, the solution is to open the file for write-binary instead of just write. Then you need to convert your string to bytes and write that to your file. The following worked for me (tl;dr last two lines):

templates = TemplateLookup(directories=[input_dir,], module_directory=mako_module_dir)

try:
    rendered_output = templates.get_template(target_template).render_unicode(**data)
except:
    print(mako_exceptions.text_error_template().render())
    return
with open(f'{output_dir}{os.path.sep}{os.path.basename(output_filename)}', 'wb') as outfile:
    outfile.write(rendered_output.encode())