【问题标题】:python - write non-ascii characters to filepython - 将非ASCII字符写入文件
【发布时间】: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


【解决方案1】:

您可以尝试使用“编解码器”模块:

import codecs

with codecs.open('filename', 'w', encoding='utf-8') as out:  
    out.write(u'some text')

【讨论】:

  • 在 Python 2 中使用“u 字符串”会有所帮助
猜你喜欢
  • 2014-04-05
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多