Python 2.6: 参数 1 必须是字符串或固定缓冲区,对于 UTF-8 字符串的字节数组,不能是字节数组

Python 2.6: argument 1 must be string or pinned buffer, not bytearray for bytearray of UTF-8 string

在Python 2.6.8 中写入unicode 字符串时出现以下错误:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    f.write(bytearray(u, 'utf_8'))
TypeError: argument 1 must be string or pinned buffer, not bytearray

当运行 Python 2.7.8 中的代码一切正常时,字符串打印和写入正确。

这是代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

u = u"Möwe"

print u

with open("testout", "w") as f:
    f.write(bytearray(u, 'utf_8'))

包含 4 字节 UTF-8 字符的字符串会出现相同的行为。

Python 2.6二进制细节:

$ python26 -v -c 'exit' 2>&1 | grep -A 1 '^Python'
Python 2.6.8 (unknown, Nov  7 2012, 14:47:45) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2

文件默认以 ascii 模式打开,无法写入 unicode 字节,因为它们包含 non-ascii 个字符。您必须以二进制模式打开文件:

with open("testout", "wb") as f:
    f.write(bytearray(u, 'utf_8'))

Python 2.6 docs on open()