2016-01-23 70 views
0

在Python 2.6.8我寫一個Unicode字符串時,遇到下列錯誤:Python的2.6:1的參數必須是字符串或固定緩衝區,而不是字節組的字節組UTF-8字符串的

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')) 

相同的行爲occures包含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 

回答

0

該文件在默認情況下每ASCII模式打開,unicode的字節不能寫,因爲它們包含非ASCII字符。你必須以二進制方式打開文件:

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

Python 2.6 docs on open()

相關問題