2014-03-03 134 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非常有用,謝謝! –

相關問題