Skip to content

Instantly share code, notes, and snippets.

@pandorica-opens
Created October 26, 2020 12:51
Show Gist options
  • Select an option

  • Save pandorica-opens/282cc6e8efcd8f211c6e1514200718cf to your computer and use it in GitHub Desktop.

Select an option

Save pandorica-opens/282cc6e8efcd8f211c6e1514200718cf to your computer and use it in GitHub Desktop.
We're working with a list of flowers and some information about each one. The create_file function writes this information to a CSV file. The contents_of_file function reads this file into records and returns the information in a nicely formatted block. Turns the data in the CSV file into a dictionary using DictReader.
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 into a dictionary
dictionary = csv.DictReader(f)
# Process each item of the dictionary
for row in dictionary:
return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
return return_string
#Call the function
print(contents_of_file("flowers.csv"))
@krlybag
Copy link

krlybag commented May 24, 2021

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 into a dictionary
reader = csv.DictReader(file)
# 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"))

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