1

再次使用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

我该如何纠正这个问题?

4

12 回答 12

4
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")

def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file
  create_file(filename)

  # Open the file
  with open(filename) as f:
    # Read the rows of the file
    rows = csv.reader(f)
    headers = next(rows)
    # Process each row
    for row in rows:
      name, color, ty = row
      # Format the return string for data rows only          
      return_string += "a {} {} is {}\n".format(color , name, ty)

  return return_string

# Call the function
print(contents_of_file("flowers.csv"))
于 2020-08-14T06:10:13.037 回答
2

csv.reader在实例化对象之前,您可以通过读入并丢弃它来跳过一行:

  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
于 2020-06-01T08:38:13.347 回答
1

使用模块 csv 和 os 的方法,这将是上述问题的完整代码,

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:
    # discard/ignore header row
    file.readline()
    # Read the rows of the file
    rows = csv.reader(file)
    # Process each row
    for row in rows:
      name,color,type = row
      # Format the return string for data rows only
      return_string += "a {} {} is {}\n".format(color, name, type)
  return return_string

#Call the function
print(contents_of_file("flowers.csv"))
于 2020-07-18T12:24:22.570 回答
1
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 f:
    # Read the rows of the file
    rows = csv.reader(f)
    # Process each row
    line_count = 0
    for row in rows:
      name,color,typ = row
      # Format the return string for data rows only
      if line_count != 0:
        return_string += "a {} {} is {}\n".format(name,color,typ)
      line_count += 1
    
  return return_string

#Call the function
print(contents_of_file("flowers.csv"))
于 2021-01-10T02:14:28.663 回答
0

我对问题的解决方案

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")

def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file
  create_file(filename)

  # Open the file
  with open(filename) as f:
    # Read the rows of the file
    rows = csv.reader(f)
    headers = next(rows)
    # Process each row
    for row in rows:
      name, color, ty = row
      # Format the return string for data rows only          
      return_string += "a {} {} is {}\n".format(color , name, ty)

  return return_string

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

于 2020-08-09T17:14:47.037 回答
0

我是这样做的

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, "r") as file:
    # Read the rows of the file
    rows = csv.reader(file)
    # Process each row
    counter = 0
    for row in rows:
      name, color, ftype = row
      # Format the return string for data rows only
      if counter != 0:
        return_string += "a {} {} is {}\n".format(color, name, ftype)
      counter = 1
  return return_string
    
#Call the function
print(contents_of_file("flowers.csv"))
于 2021-05-27T12:46:23.947 回答
0

必须以正确的顺序输入所需的输出格式。我自己试过这个。

return_string += "a {} {} is {}\n".format(name, color, ty)

通过切换变量“名称”和“颜色”格式位置来编辑此语句。

return_string += "a {} {} is {}\n".format(color, name, ty)

这肯定会奏效。!

于 2020-07-25T10:57:07.887 回答
0
import csv

创建一个包含数据的文件

from typing import List

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")

读取文件内容并格式化每一行的信息

def contents_of_file(filename):
    return_string = ""

# Call the function to create the file
create_file(filename)

# Open the file
with open(filename) as f:
    # Read the rows of the file
    rows = csv.reader(f)
    headers = next(rows)
    # Process each row
    for row in rows:
        name, color, ty = row
        # Format the return string for data rows only          
        return_string += "a {} {} is {}\n".format(color , name, ty)

return return_string

# Call the function
print(contents_of_file("flowers.csv"))
于 2020-07-31T19:19:15.317 回答
0

改变

return_string += "a {} {} is {}\n".format(name, color, ty)

return_string += "a {} {} is {}\n".format(color, name, ty)
于 2020-06-01T08:39:34.940 回答
0

我是这样做的:

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 f:
    # Read the rows of the file
    rows = csv.DictReader(f)
    # Process each row
    for row in rows:
      name, color, ty = row
      # Format the return string for data rows only
      return_string += "a {} {} is {}\n".format(row[color], row[name], row[ty])
  return return_string

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

输出是这样的:

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
于 2021-08-29T10:17:51.600 回答
0

导入操作系统导入csv

创建一个包含数据的文件

def create_file(filename): with open(filename, "w") as file: file.write("name,color,type\n") file.write("carnation,pink,annual\n") file.write( "水仙花,黄色,多年生\n") file.write("鸢尾花,蓝色,多年生\n") file.write("一品红,红色,多年生\n") file.write("向日葵,黄色,一年生\n ")

def content_of_file(文件名): 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.DictReader(file)
  # Process each row
  for row in rows:
    color, name, type = row
    # Format the return string for data rows only          
    return_string += "a {} {} is {}\n".format(row["color" , row["name"], row["type"])

return return_string

调用函数

打印(contents_of_file(“flowers.csv”))

于 2020-08-14T06:13:19.717 回答
0

解决“如何跳过带有字段名称的标题记录?”的问题。可以使用 next():

with open('my_file.csv', 'r') as f:
    headers = next(f)
    # do something with rest of the lines
于 2020-06-01T10:46:38.787 回答