【发布时间】:2014-04-04 14:39:20
【问题描述】:
我在 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)
我该如何解决这个问题?谢谢。
【问题讨论】:
-
您确定不想
decode('utf-8')将您的utf8 字符串转换为字节串吗? -
您有示例或源链接吗?
-
你试过用
"au"模式打开文件吗? -
是的,我试过“au”模式。我遇到了同样的错误。
-
您可以尝试使用文档中描述的模式
"ab"(二进制模式)来避免文本模式吗?
标签: utf-8 python-2.x