【问题标题】:Additional carriage return created when writing mako rendered template to a file将 mako 渲染模板写入文件时创建的附加回车
【发布时间】:2026-02-02 18:30:01
【问题描述】:

我正在使用 mako 模板库生成一个 test.txt 文件,但是生成的文件在每行之间包含额外的空行。

我发现了一个关于这个问题的类似问题here 并且提出的解决方案建议使用标记安全,但我不相信这也适合我的情况,因为它考虑将文本格式化为参数在渲染模板时,这不是我想做的(我不想更改模板中的大部分文本,我只是输入了一些变量)。

我认为还值得一提的是,如果我在 Python 中打印渲染的模板,它会以正确的格式打印;额外的行只出现在我使用 Python 的文件 write() 将模板数据写入 (test.txt) 的文件中。

【问题讨论】:

    标签: python mako


    【解决方案1】:

    支持this answer,解决方案是打开文件进行写入二进制而不是只写入。然后,您需要将字符串转换为字节并将其写入文件。以下对我有用(tl; dr最后两行):

    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())
    

    【讨论】: