2014-03-03 141 views
5

我在Linux上并希望将字符串(在utf-8中)写入txt文件。这是我的代码:python - 将非ascii字符写入文件

# -*- coding: UTF-8-*- 

import os 
import sys 


def __init__(self, dirname, speaker, file, exportFile): 

     text_file = open(exportFile, "a") 

     text_file.write(speaker.encode("utf-8")) 
     text_file.write(file.encode("utf-8")) 

     text_file.close()  

当我在Windows上,它的工作原理。但在Linux上,我得到这个错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position in position 36: ordinal not in range(128) 

我该如何解决这个问题?谢谢。

+1

你确定你不想'解码(“utf-8”)'你的UTF8字符串转换为字节串? – mgilson

+0

你有一个样本或链接到你的来源? – alvas

+0

你有没有尝试在'“au”模式下打开文件? –

回答

7

您可以尝试使用“解码器”模块:

import codecs 

with codecs.open('filename', 'w', encoding='utf-8') as out: 
    out.write(u'some text') 
+1

我试过了,但我得到了同样的错误。 – user3375111

+0

使用Python 2可以帮助使用“u字符串” – dugres

+0

这对我的Python3非常有用,谢谢! –

相关问题