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

Avi*_*Raj 12 python python-3.x

我正在尝试将数据字节列表写入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'))
Run Code Online (Sandbox Code Playgroud)

但它会导致以下错误:

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

datas 是字节字符串列表.

print(datas)
Run Code Online (Sandbox Code Playgroud)

产量

[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]
Run Code Online (Sandbox Code Playgroud)

我想将上面的列表打印为CSV文件中的第一行,并解码Unicode字符.也就是说,\xc3\x97应该转换为它的相应字符.

tob*_*s_k 9

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

根据您的操作系统,您可能还需要指定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])
Run Code Online (Sandbox Code Playgroud)

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


Jac*_*k M 5

此错误仅意味着您传递给的内容bytes(您想要转换为字节序列的字符串)实际上不是字符串。它并不具体意味着参数已经是 type 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
Run Code Online (Sandbox Code Playgroud)