簡體   English   中英

讀寫 CSV 文件

[英]Reading & Writing CSV Files

我開始學習 Python 並且我正在 Coursera 上學習關於自動化和 IT 使用它的 Google 課程。 練習測驗:閱讀和編寫 CSV 文件中,第一個問題是:

我們正在處理一份鮮花清單和每一種鮮花的一些信息。 create_file function 將此信息寫入 CSV 文件。 contents_of_file function 將該文件讀入記錄並以格式良好的塊返回信息。 填寫contents_of_file function 的空白,使用DictReader將 CSV 文件中的數據轉換為字典。

給出答案后,我收到“不正確。出了點問題!就這個問題聯系 Coursera 支持!我在這里找到了一個頁面並復制了該代碼,但答案總是一樣的。所以我聯系了 Coursera,但他們說沒有他們的問題。這就是我提供的代碼:

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

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

有沒有人遇到過同樣的問題? 或者你能解釋一下為什么它不起作用嗎?

在此處添加瀏覽器的控制台日志。 嘗試使用 Firefox、Chrome 和現在的 Opera。 控制台日志

由於它是一個在線評估平台,出於安全原因,它可能會禁止import OS等操作。 此外,它在您的代碼中沒有做任何事情。 您是否嘗試刪除該行?

看來您錯過了閱讀器 function 中的一些選項( delimiternewline='' )。 這是工作代碼:

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

請記住, newline = ''用於 python3,必須設置分隔符才能正確讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM