【发布时间】:2022-01-23 21:44:39
【问题描述】:
我创建了一个 csv 文件,如下所示:
%%writefile employee2.csv
name, department, birthday month
John Smith, Accounting, November, 6
Erica Meyers, IT, March
现在我想用 DictRead 读取 csv 文件的每一行,但它不读取第二行 (John Smith)
import csv
with open('employee2.csv', newline='') as csv_file:
csv_reader = csv.DictReader(csv_file, restkey='day', skipinitialspace=True)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are: {", ".join(row)}')
else:
print(f'{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
line_count += 1
输出是:
Column names are: name, department, birthday month, day
Erica Meyers works in the IT department, and was born in March.
现在,我有两个问题: 1-为什么它不读取文件的第二行并打印出来? 2- 如果我想在打印命令中添加restkey,我该怎么做?
最好的问候,
【问题讨论】: