【问题标题】:Python decode list elements from utf16Python 解码来自 utf16 的列表元素
【发布时间】:2019-06-11 09:48:50
【问题描述】:

我对从 python 打开的文本文件创建的阅读列表有问题。这是我的代码:

if orderFilesListCount >= 1:
     orderContents = list()
     with open(os.path.join(directory,fileName), "r") as f:
          for line in f:
               orderContents.append(line)

orderContents 看起来像(这只是用于演示目的的段落):

'\x000\x001\x005\x00 \x006\x003\x00 \x005\x003\x00 \x004\x004\x00\n', '\x00\n', '\x00'

我认为它是 utf-16,但是当我尝试逐个字符串解码列表字符串时,出现以下错误(因为我知道无法解码 str 对象):

AttributeError: 'str' object has no attribute 'decode'

我该怎么办?我弄错了吗?也许它不是 utf-16? 感谢您的帮助

【问题讨论】:

    标签: python decode utf-16


    【解决方案1】:

    是的,解码strings 没有意义,因为它们已经被解码。但是,可以解码bytes

    with open(os.path.join(directory,fileName), "rb") as f:  # open as binary
        data = f.read().decode("utf16")
    

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多