我想将CSV文件读入字典,这是我的代码:
import csv
import sys
with open('/Users/m/based_final.csv',mode='r') as my_input_file:
csv_reader=csv.DictReader(my_input_file)
line_count=0
for row in csv_reader:
if line_count == 0:
print(str.format('Column names are {",".join(row)}'))
line_count += 1
print(str.format('\t{row["Indication"]} {row["Name"]} {row["Drug id"]} {row["Synonyms"]} '))
line_count += 1
print('Processed {line_count} lines.')
但是我得到这个错误: KeyError:“”,“”。
这是数据的样子:
Indication Name Drug id Synonyms
for_treatment bivalirudin ['db00006', 'btd00076'] ['bivalirudina', 'bivalirudinum', 'hirulog']
for_alteplase a name ['db00009', 'btd00050', 'biod00050'] ['alteplase (genetical recombination)', 'alteplase, recombinant']
任何想法如何解决? 谢谢
答案 0 :(得分:0)
这是您的代码,其中固定了注释,告诉了我更改的内容,但是,您需要更改文件的第一行才能使用此代码。 CVS文件的第一行需要格式化。您词典中想要的每个键都必须在其后有一个逗号。昏迷周围也不能有任何空间。
import csv
import sys
with open('/Users/m/based_final.csv',mode='r') as my_input_file:
csv_reader=csv.DictReader(my_input_file)
line_count=0
for row in csv_reader:
if line_count == 0:
print(str.format(f'Column names are {", ".join(row)}')) # an f added before the single quotes and a space after the coma for readibility
line_count += 1
print(str.format(f'\t{row["Indication"]} {row["Name"]} {row["Drug id"]} {row["Synonyms"]} ')) # same thing with the f
line_count += 1
print(f'Processed {line_count} lines.') # ditto