【发布时间】:2015-04-03 10:54:09
【问题描述】:
这个text file(仅30字节,内容为'(Ne pas r\xe9pondre a ce message)')可以打开并成功插入dict:
import json
d = {}
with open('temp.txt', 'r') as f:
d['blah'] = f.read()
with open('test.txt', 'w') as f:
data = json.dumps(d)
f.write(data)
但是不可能将dict 转储到 JSON 文件中(参见下面的回溯)。为什么?
我尝试了各种 SO 问题提供的许多解决方案。我能得到的最接近的解决方案是this answer。使用它时,我可以转储到文件,但是 JSON 文件看起来像这样:
# test.txt
{"blah": "(Ne pas r\u00e9pondre a ce message)"}
而不是
# test.txt
{"blah": "(Ne pas répondre a ce message)"}
追溯:
File "C:\Python27\lib\json\encoder.py", line 270, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 9: invalid continuation byte
[Finished in 0.1s with exit code 1]
【问题讨论】: