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