【发布时间】:2014-04-05 17:10:21
【问题描述】:
我在 Linux 上,想将字符串(utf-8 格式)写入 txt 文件。试了很多方法,总是报错:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position in position 36: ordinal not in range(128)
有什么办法,如何只写入文件的 ascii 字符?并忽略非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()
谢谢。
【问题讨论】:
-
在写入前去除 非 ascii 字符?
-
你试过
speaker.encode('utf-8', errors='ignore')吗?但是,我相信您做错了其他事情,因为您不应该首先出现该错误。你能告诉我们speaker和file是什么吗?此外,如果您想将二进制数据写入文件,您应该以二进制模式打开文件:open(export_file, 'ab').