Python CSV Files Tutorial

CSV → 2D List

Reading a CSV File into a 2 Dimensional Python List

Sometimes you will need to read data stored in comma separated value (CSV) files. You can use the csv module in order to achieve this.

import csv

f = open('mycsvfile.csv','r')
reader = csv.reader(delimiter = ',')

items = []
for row in reader:
     items.append(row)

CSV files usually use a comma as the delimiter between each data item, but sometimes might use a tab or other character instead.

Tutorial Video

YouTube Blocked? Try the Google Drive Version

2D List → CSV

Writing a 2 Dimensional List to a CSV File

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.

import csv
f = open('namesages.csv','a',newline = '')

name = input("What is your name?")
age = input("What is your age?")

row = (name,age)

writer = csv.writer(f)
writer.writerow(row)

f.close() #really important!!!

Tutorial Video

YouTube Blocked? Use the Google Drive version instead


CSV → Dictionary

Reading a CSV File into a Python Dictionary

Sometimes you want to read the data into a dictionary instead of a 2 Dimensional list. CSV reader can do this too.

import csv

f = open('people.csv','r')
reader = csv.reader(delimiter = ',')

people = {}
for row in reader:
     people[row[0]] = {'age':row[1],'color':row[2]}

Tutorial Video

Can’t access YouTube? Try the Google Drive Version.

Dictionary → CSV

Writing a Python Dictionary to a CSV File

import csv

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’

Silver

 Adapt your program so that it automatically adds the current date and time to the log.

Gold

 Adapt your program so that each ticket is given a unique job number that increments automatically.

40

Challenge 40 – Country Top Trumps

 Bronze

Create program that reads the country_csv file into a list of dictionaries.

 Silver

Create a one player top trumps game where the player picks a single card and the computer picks a card and then they see who wins.

  Gold

Extend the game so that you play a full game of top trumps with a deck of card and two players