pystache/mustache中的UnicodeDecodeError

1 投票
1 回答
1002 浏览
提问于 2025-04-17 13:46

我正在尝试使用pystache将一些数据写入文件。这些数据来自一个从谷歌文档表格导出的csv文件。当我使用pystache模板写入文件时,出现了这个错误:

UnicodeDecodeError: 'ascii' codec can't decode byte...

根据StackOverflow上其他一些问题的讨论,我应该使用.decode('utf-8'),但我仍然遇到同样的错误。

datafile = "../data.csv"
renderer = pystache.Renderer()

f=open('sample.html','w')
templateHash={}
items = []

with open(datafile, 'rb') as csvfile:
    datareader = csv.reader(csvfile, delimiter=',')
    for row in datareader:
        item = {'name' : row[2].decode('utf-8')}
        items.append(item)

templateHash['lines'] = items
f.write(renderer.render_path('sample.mustache', templateHash))
f.close

这里是完整的错误追踪信息:

Traceback (most recent call last):
  File "parsetable.py", line 15, in <module>
    f.write(renderer.render_path('sample.mustache', templateHash))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 750: ordinal     not in range(128)
[Finished in 0.3s with exit code 1]

1 个回答

1
f = codecs.open('sample.html', 'w', encoding='utf-8')

或者更好的是,使用 with

撰写回答