Often you will want to be able to save 2 Dimensional List data to a CSV file so that it isn’t deleted when your program exits. you can use csv writer to achieve this.
importcsv
f = open('animals.csv','w', newline = '')
#use 'a' instead of 'w' if you want to add to the csv, not write a new one.
writer = csv.writer(f)
# example 2D List
l = [["dog",2],["cat",15],["mouse",34]]
for item in l:
writer.writerow(item)
f.close() #really important!!!
Sometimes you want to read the data into a dictionary instead of a 2 Dimensional list. CSV reader can do this too.
importcsv
f =open('people.csv','r')
reader = csv.reader(f, delimiter =',')
people = {}
for row in reader:
people[row[0]] = {'age':row[1],'color':row[2]}
importcsv
cols = ["name","strength","speed"]
players = [
{"name":"bob","strength":45,"speed":25.5},
{"name":"sally","strength":22,"speed":50}
]
f =open("players.csv", "w", newline='')
writer = csv.DictWriter(f, fieldnames = cols)
writer.writeheader() #If you want a header row in your csv
writer.writerows(players)
f.close()
Challenge 37
Challenge 37 – Animal Stats Printer
Bronze
Read the CSV file animal_data.csv into a 2 dimensional list and print out the items.
Silver
Print out the list in order of population
Gold
Ask the user to type in a column selection(e.g. “average age”) and have the program sort the items in that order.
38
Challenge 38 – Animal Stats Adder
Bronze
Write a program that allows you to add an extra animal to the animal_facts.csv file. (you might want to use append ‘a’ mode instead of write ‘w’ mode.)
Silver
Allow the user to keep adding more animals until the type an empty string.
Gold
Once the user has finished adding, print out the animals in alphabetical order.
39
Challenge 39 – IT Support Log
Bronze
Ask the user to input their name and a description of their IT issue. Save the issue to the file ‘ict_issue_log.txt’