生成的文件以 GBK 方式编码,但期望以 UTF-8 读取,导致乱码。
with open(f"file.j2",'w+') as fout:
content = template.render()
fout.write(content)解决方案
将 open() 处的 w+ 改为 wb ,在 template.render() 后调用 encode('utf-8')。
with open(f"file.j2",'wb') as fout:
content = template.render().encode('utf-8')
fout.write(content)