gpt4 book ai didi

python-3.x - 有人可以帮我吗。我在用Python编写此代码时遇到问题

转载 作者:行者123 更新时间:2023-12-03 09:12:42 24 4
gpt4 key购买 nike

我们正在处理一张鲜花 list ,以及有关每一种鲜花的一些信息。 create_file函数将此信息写入CSV文件。 contents_of_file函数将该文件读入记录,并以格式正确的块形式返回信息。使用DictReader填充contents_of_file函数的间隙,以将CSV文件中的数据转换为字典。

import os
import csv

# Create a file with data in it
def create_file(filename):
with open(filename, "a") 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 into a dictionary
f = csv.reader(file)
# Process each item of the dictionary
for row in f:
name, color, type = row
return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
return return_string

#Call the function
print(contents_of_file("flowers.csv"))

[See the error][1]


[1]: /image/UycSc.jpg

最佳答案

这就是答案,@ Pratik Panda在您使用过reader()的代码中,但是在问题陈述中,他们说必须使用 DictReader()

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 into a dictionary
f = csv.DictReader(file)
# Process each item of the dictionary
for row in f:
return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
return return_string

#Call the function
print(contents_of_file("flowers.csv"))

关于python-3.x - 有人可以帮我吗。我在用Python编写此代码时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61587360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com