再次使用flowers的CSV文件,填充contents_of_file函数的空白来处理数据,而不是把它变成字典。如何跳过带有字段名称的标题记录?
import os
import csv
# Create a file with data in it
def create_file(filename):
with open(filename, "w") as file:
file.write("name,color,type\n")
file.write("carnation,pink,annual\n")
file.write("daffodil,yellow,perennial\n")
file.write("iris,blue,perennial\n")
file.write("poinsettia,red,perennial\n")
file.write("sunflower,yellow,annual\n")
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = ""
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename) as file:
# Read the rows of the file
rows = csv.reader(file)
rows = list(rows)
# Process each row
for row in rows:
name, color, ty = row
# Format the return string for data rows only
if row != rows[0]:
return_string += "a {} {} is {}\n".format(name, color, ty)
return return_string
#Call the function
print(contents_of_file("flowers.csv"))
提交我的答案后,将显示以下消息:
Not quite, contents_of_file returned:
a carnation pink is
annual
a daffodil yellow is perennial
a iris blue is
perennial
a poinsettia red is perennial
a sunflower yellow
is annual
The output should be:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a
red poinsettia is perennial
a yellow sunflower is annual
我该如何纠正这个问题?