【问题标题】:Python 2.6: argument 1 must be string or pinned buffer, not bytearray for bytearray of UTF-8 stringPython 2.6:参数 1 必须是字符串或固定缓冲区,而不是 UTF-8 字符串的字节数组的字节数组
【发布时间】:2016-04-30 10:11:06
【问题描述】:

在 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

【问题讨论】:

    标签: file unicode utf-8 bytearray python-2.6


    【解决方案1】:

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

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

    Python 2.6 docs on open()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多