Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Utf 8 python-将非ascii字符写入文件_Utf 8_Python 2.x - Fatal编程技术网

Utf 8 python-将非ascii字符写入文件

Utf 8 python-将非ascii字符写入文件,utf-8,python-2.x,Utf 8,Python 2.x,我在Linux上,希望将字符串(utf-8)写入txt文件。这是我的代码: # -*- 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.writ

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

# -*- 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)
我怎样才能解决这个问题?谢谢。

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


您确定不想
解码('utf-8')
将utf8字符串转换为bytestring吗?您是否有指向源代码的示例或链接?您是否尝试过在
“au”
模式下打开文件?是的,我尝试了“au”模式。我遇到了同样的错误。您能尝试使用模式
“ab”
(二进制模式)吗?文档中描述了这种模式以避免文本模式?在Python 2中,使用“u字符串”可能会有所帮助
import codecs

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