带有pystache / mustache的UnicodeDecodeError

时间:2013-01-26 22:08:08

标签: python mustache

我正在尝试使用pystache将一些数据写入文件。数据来自从谷歌文档电子表格导出的csv文件。使用pystache模板编写文件时,我收到此错误:

UnicodeDecodeError:'ascii'编解码器无法解码字节...

根据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 个答案:

答案 0 :(得分:1)

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

或者更好的是,使用with