当我使用open()
打开文件时,我无法写入unicode字符串。我了解到我需要使用codecs
并使用Unicode编码打开文件(请参阅http://docs.python.org/howto/unicode.html#reading-and-writing-unicode-data)。如何使用Unicode编码创建临时文件?
现在我需要创建一些临时文件。我试图使用tempfile
库,但它没有任何编码选项。当我尝试写任何unicode字符串的临时文件tempfile
,它失败:
#!/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返回的字符串。
是的。所以,不需要用一些神奇的unicode选项来打开tempfile,这足以编写一个明确编码的字符串:'fh。写(u'föobār'.encode('utf-8'))'。如果大多数角色都是CJK,请用'utf-16'替换'utf-8'。 – 9000
@ 9000:如果您使用'utf-16',请注意此方法。如果这样做,您将不得不一次写入整个文件,因为encode('utf-16')也会输出文件BOM。如果你有几个字符串写入同一个文件,第一个应该使用.encode('utf-16'),而后面的使用.encode('utf-16-le')来发送BOM。使用一些神奇的unicode选项可以避免这个陷阱。 – kriss
'“abc”'是Python 3中的一个Unicode字符串,或者存在于'from __future__ import unicode_literals'中。 – jfs