python-写入文件(忽略非ASCII字符)
我在使用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()
谢谢。
3 个回答
0
你可以在写入之前先解码你的输入字符串。
text = speaker.decode("utf8")
with open(exportFile, "a") as text_file:
text_file.write(text.encode("utf-8"))
text_file.write(file.encode("utf-8"))
0
你可以使用 codecs
这个模块:
import codecs
text_file = codecs.open(exportFile,mode='a',encoding='utf-8')
text_file.write(...)
0
试试使用 codecs
模块。
# -*- coding: UTF-8-*-
import codecs
def __init__(self, dirname, speaker, file, exportFile):
with codecs.open(exportFile, "a", 'utf-8') as text_file:
text_file.write(speaker.encode("utf-8"))
text_file.write(file.encode("utf-8"))
另外,要注意你的 file
变量的名字和内置的 file
函数是重复的,这可能会引起问题。
最后,我建议你看看 http://www.joelonsoftware.com/articles/Unicode.html,这样可以更好地理解什么是 Unicode。还可以根据你的 Python 版本查看以下页面,了解如何在 Python 中使用它: