【问题标题】:python-write to file (ignore non-ascii chars)python写入文件(忽略非ascii字符)
【发布时间】: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')吗?但是,我相信您做错了其他事情,因为您不应该首先出现该错误。你能告诉我们speakerfile是什么吗?此外,如果您想将二进制数据写入文件,您应该以二进制模式打开文件:open(export_file, 'ab').

标签: python file utf-8


【解决方案1】:

您可以使用codecs 模块:

import codecs
text_file = codecs.open(exportFile,mode='a',encoding='utf-8')
text_file.write(...)

【讨论】:

    【解决方案2】:

    尝试使用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 中使用它:

    【讨论】:

    • 我尝试了很多方法(也包括编解码器),但我总是遇到同样的错误。因此,我想忽略非 ascii 字符并仅写入文件 ascii。 (我的程序中没有名为“file”的变量,这只是示例)。
    • 您的变量的类型似乎是str。因此,当您执行str.encode('utf-8') 时,python 会自动将您的str 转换为unicode,方法是使用系统默认编码(python2 中的 ascii)对其进行编码。鉴于您的错误消息中提到了“ascii”,我想这是这种隐式转换失败的原因。你确定所有你的变量都是unicode类型的吗?
    【解决方案3】:

    您可以在编写输入字符串之前对其进行解码;

    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"))    
    

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多