【发布时间】:2012-05-16 11:26:09
【问题描述】:
当我使用open() 打开文件时,我无法编写 unicode 字符串。我了解到我需要使用 codecs 并使用 Unicode 编码打开文件(请参阅 http://docs.python.org/howto/unicode.html#reading-and-writing-unicode-data)。
现在我需要创建一些临时文件。我尝试使用tempfile 库,但它没有任何编码选项。当我尝试使用 tempfile 在临时文件中写入任何 unicode 字符串时,它会失败:
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
import tempfile
with tempfile.TemporaryFile() as fh:
fh.write(u"Hello World: ä")
fh.seek(0)
for line in fh:
print line
如何在 Python 中使用 Unicode 编码创建临时文件?
编辑:
-
我使用的是 Linux,我收到的代码错误消息是:
Traceback (most recent call last): File "tmp_file.py", line 5, in <module> fh.write(u"Hello World: ä") UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 13: ordinal not in range(128) - 这只是一个例子。在实践中,我正在尝试编写一些 API 返回的字符串。
【问题讨论】:
标签: python unicode temporary-files