我创建了一个csv文件如下所示:
%%writefile employee2.csv
name, department, birthday month
John Smith, Accounting, November, 6
Erica Meyers, IT, March现在我想用DictRead读取csv文件的每一行,但它不读取第二行(John )
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添加到print命令中,我如何做到这一点?
诚挚的问候,
发布于 2021-12-22 19:52:31
使用csv.DictReader时,在开始逐行读取文件(for row in csv_reader:)之前,它将独立地读取文件。不需要查看是否正在阅读第一行(对于fieldnames)。
若要将restkey添加到打印中,请将其从行字典中删除,然后打印弹出的值。见this。
import csv
with open('tmp1.csv', newline='') as csv_file:
csv_reader = csv.DictReader(csv_file, restkey='day', skipinitialspace=True)
cols = csv_reader.fieldnames
print('Column names are: ', cols)
for row in csv_reader:
day = row.pop('day', None)
if day != None:
print(f'{row["name"]} works in the {row["department"]} department, and was born on {row["birthday month"]} {day[0]}.')
else:
print(f'{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')指纹:
Column names are: ['name', 'department', 'birthday month']
John Smith works in the Accounting department, and was born on November 6.
Erica Meyers works in the IT department, and was born in March.https://stackoverflow.com/questions/70452916
复制相似问题