Skip to content

Instantly share code, notes, and snippets.

@pandorica-opens
Created October 26, 2020 12:53
Show Gist options
  • Save pandorica-opens/6d81943526aa3c12da740b11eb7edec1 to your computer and use it in GitHub Desktop.
Save pandorica-opens/6d81943526aa3c12da740b11eb7edec1 to your computer and use it in GitHub Desktop.
Process the flowers data again without turning it into a dictionary.
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 f:
# Read the rows of the file
rows = csv.reader(f)
# Skips the headers
next(rows)
# Process each row
for row in rows:
name, color, typeflower = row
# Format the return string for data rows only
return_string += "a {} {} is {}\n".format(color, name, typeflower)
return return_string
#Call the function
print(contents_of_file("flowers.csv"))
@FatCatLikesBeer
Copy link

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.DictReader(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(row["color"], row["name"], row["type"])
  return return_string

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

@sairam7488
Copy link

showing error on line 31

@Codehunter-py
Copy link

Codehunter-py commented Sep 20, 2022

@sairam7488 could you paste here error message?

@sairam7488
Copy link

Error on line 31:
return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
^
IndentationError: unexpected indent

@Codehunter-py
Copy link

@sairam7488 Try to align return_string variable for the loop. In my case, there is no error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment