【发布时间】: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')吗? (另外,你不应该将它应用于每个元素,而不是整个列表吗?) -
另外,对于
writerows,datas不应该是一个列表列表吗? -
@tobias_k 显示
TypeError: coercing to str: need a bytes-like object, list found -
仍然不确定我是否真的理解你想要做什么。您能否发布您正在使用的确切
datas以及它在 CSV 中的确切外观? (datas中缺少一个',所以这似乎被裁剪了。)另外,\n应该如何在 CSV 中呈现,这应该是单行还是多行?
标签: python python-3.x