再用花的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
如何纠正这个问题?
你可以在实例化这个函数之前,通过读入并丢弃这一行来跳过 csv.reader
对象,或者你可以直接丢弃第一行,将其转换为一个列表并从1开始循环。
with open(filename) as file:
file.readline() # header row
for row in csv.reader(file):
# do stuff
或者你可以直接丢弃第一行 通过转换为一个列表并从1开始循环。
with open(filename) as file:
for row in list(csv.reader(file))[1:]:
# do stuff
或者像这样,如果你想在迭代器上循环,而不把所有的行加载到内存中。
with open(filename) as file:
first = True
for row in csv.reader(file):
if first:
first = False
continue
# do stuff
或者你可能更喜欢使用csv阅读器的字典形式,这样你就不会丢弃头行,而是用它来提供字典键。
with open(filename) as file:
for row in csv.DictReader(file):
# row is now a dictionary, e.g.
# {'color': 'pink', 'type': 'annual', 'name': 'carnation'}
# do stuff
改变
return_string += "a {} {} is {}\n".format(name, color, ty)
至
return_string += "a {} {} is {}\n".format(color, name, ty)
为了解决" 如何跳过带有字段名的头记录?"的问题。可以使用next()。
with open('my_file.csv', 'r') as f:
headers = next(f)
# do something with rest of the lines