【问题标题】:TypeError: encoding or errors without a string argumentTypeError:没有字符串参数的编码或错误
【发布时间】:2015-06-08 14:34:14
【问题描述】:

我正在尝试将数据字节列表写入 CSV 文件。因为它是一个字节字符串列表,所以我使用了下面的代码:

with open(r"E:\Avinash\Python\extracting-drug-data\out.csv", "wb") as w:
    writer = csv.writer(w)
    writer.writerows(bytes(datas, 'UTF-8'))

但是会导致如下错误:

TypeError:没有字符串参数的编码或错误

datas 是一个字节串列表。

print(datas)

产量

[b'DB08873', b' MOLSDFPDBSMILESInChIView Structure \xc3\x97Structure for DB08873 (Boceprevir) Close', b'394730-60-0', b'LHHCSNFAOIFYRV-DOVBMPENSA-N', b'Organic acids and derivatives  ', b'Food increases exposure of boceprevir by up to 65% relative to fasting state. However, type of food and time of meal does not affect bioavailability of boceprevir and thus can be taken without regards to food.  \r\nTmax = 2 hours;\r\nTime to steady state, three times a day dosing = 1 day;\r\nCmax]

我希望将上述列表打印为 CSV 文件中的第一行,并解码 Unicode 字符。也就是说,\xc3\x97 应该转换成它对应的字符。

【问题讨论】:

  • 既然要将字节转换回字符串,不应该是str(datas, 'UTF-8')吗? (另外,你不应该将它应用于每个元素,而不是整个列表吗?)
  • 另外,对于writerowsdatas 不应该是一个列表列表吗?
  • @tobias_k 显示TypeError: coercing to str: need a bytes-like object, list found
  • 仍然不确定我是否真的理解你想要做什么。您能否发布您正在使用的确切 datas 以及它在 CSV 中的确切外观? (datas 中缺少一个',所以这似乎被裁剪了。)另外,\n 应该如何在 CSV 中呈现,这应该是单行还是多行?

标签: python python-3.x


【解决方案1】:

看来您的datas 已经是字节格式,所以要将其转换为UTF-8 字符串,您必须使用str,而不是bytes!此外,您必须单独转换 datas 中的每个元素,而不是一次转换整个列表。最后,如果你想将datas 作为一行添加到out.csv,你必须使用writerow,而writerows 会一次写入所有行,因此会期望一个列表列表。

根据您的操作系统,您可能还必须在打开文件时指定encoding。否则它将使用操作系统的默认编码,这可能会完全不同。

似乎做你想做的事。结果是一个 CSV 文件,其中包含一行1 UTF-8 格式的数据,\xc3\x97 被解码为×

import csv
with open(r"out.csv", "w", encoding='UTF-8') as w:
    writer = csv.writer(w)
    writer.writerow([str(d, 'UTF-8') for d in datas])

1) 请注意,datas 中的最后一项包含一些换行符,因此将分成几行。这可能不是你想要的。或者这是您的datas 列表中的一个小故障?

【讨论】:

  • 附录:如果你想解码 unicode 但保持\n 转义,你可以试试repr(str(d, 'UTF-8')),但我不确定这是否是你想要的。这也会将所有字符串包装在''
  • 试过了,但它显示TypeError: 'str' does not support the buffer interface
  • @AvinashRaj 我得到了那个错误,通过将文件模式从 wb 更改为 w 来修复它。 (我认为 b(二进制)对于 CSV 文件没有意义)抱歉,忘记提及该更改。
  • 它让我发疯。如果我删除了wb 中的b,它会显示UnicodeEncodeError: 'charmap' codec can't encode character '\u221e'。无法将 unicode char 转换为字符串。
  • 如果你有时间,就跳到chat.stackoverflow.com/rooms/80049/temp。我要为此设置一个赏金..
【解决方案2】:

这个错误仅仅意味着你传递给bytes的东西(你想要转换为字节序列的字符串)实际上不是一个字符串。 not 确实意味着参数已经是 bytes 类型,只是它不是字符串。

>>> bytes(b"", encoding="utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding without a string argument
>>> bytes(None, encoding="utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding without a string argument
>>> bytes(12, encoding="utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding without a string argument

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 2018-10-16
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2015-09-18
    • 2017-03-23
    • 2021-07-01
    相关资源
    最近更新 更多