“file.write”中出错,参数类型错误

2024-06-28 10:57:07 发布

您现在位置:Python中文网/ 问答频道 /正文

再次使用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:
    fieldnames = ['type', 'name', 'color']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    file.write({'type': 'annual', 'name': 'carnation' , 'color': 'pink'})
    file.write({'type': 'perennial','name': 'daffodil' , 'color': 'yellow'})
    file.write({'type': 'perennial','name': 'iris' , 'color': 'blue'})
    file.write({'type': 'perennial','name': 'poinsettia' , 'color': 'red'})
    file.write({'type': 'annual', 'name': 'sunflower', 'color': 'yelolow'})
   # 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('flowers.csv', 'r') as file:
    # Read the rows of the file
    rowss = csv.reader(file)
    header = next(rowss)
    if header != None:
      for row in rowss:
        # Format the return string for data rows only
        return_string = "a {} {} is {}\n".format(row['color'], row['name'], row['type'])
        print(return_string)


#Call the function

print(contents_of_file("flowers.csv"))

它将错误显示为:

Error on line 42:
    print(contents_of_file("flowers.csv"))
Error on line 26:
    create_file(filename)
Error on line 9:
    file.write({'type': 'annual', 'name': 'carnation' , 'color': 'pink'})
TypeError: write() argument must be str, not dict

Tags: ofcsvthenametypecreatecontentsfilename
1条回答
网友
1楼 · 发布于 2024-06-28 10:57:07

file.write()更改为writer.writerow()file对象没有接受字典的方法。要编写字典,请使用csv.DictWriter()writer对象。 此外,这里:

with open('flowers.csv', 'r') as file:

我认为您不打算硬编码文件名ad'flowers.csv',您已经将文件名作为参数传递给了contents_of_file()方法

相关问题 更多 >