再次使用flowers的CSV文件,在不将其转换为字典的情况下,填补_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
我怎样才能纠正这个问题
在实例化
csv.reader
对象之前,可以通过读入并丢弃一行来跳过该行:或者,您可以通过转换为列表并从1循环来丢弃第一行:
或者,如果希望在迭代器上循环,而不将所有行加载到内存中,也可以这样做:
或者,您可能更喜欢使用csv读取器的字典形式,以便使用它来提供字典键,而不是丢弃标题行:
相关问题 更多 >
编程相关推荐