如何在此Python脚本中处理CSV文件

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

您现在位置: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:
        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

我怎样才能纠正这个问题


Tags: ofcsvthestringreturniscontentsfilename
3条回答
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"))

在实例化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
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"))

相关问题 更多 >