Skip to content

Instantly share code, notes, and snippets.

@jinnosux
Created May 7, 2020 20:08
Show Gist options
  • Save jinnosux/ab117af96d0ba18e946d7683dcb035bb to your computer and use it in GitHub Desktop.
Save jinnosux/ab117af96d0ba18e946d7683dcb035bb to your computer and use it in GitHub Desktop.
importing stuff from csv to db
name house birth
Adelaide Murton Slytherin 1982
Adrian Pucey Slytherin 1977
Anthony Goldstein Ravenclaw 1980
Blaise Zabini Slytherin 1979
Cedric Diggory Hufflepuff 1977
Cho Chang Ravenclaw 1979
Colin Creevey Gryffindor 1981
Dean Thomas Gryffindor 1980
Draco Lucius Malfoy Slytherin 1980
Ernest Macmillan Hufflepuff 1980
Ginevra Molly Weasley Gryffindor 1981
Gregory Goyle Slytherin 1980
Hannah Abbott Hufflepuff 1980
Harry James Potter Gryffindor 1980
Hermione Jean Granger Gryffindor 1979
Isobel MacDougal Ravenclaw 1980
Justin Finch-Fletchley Hufflepuff 1979
Lavender Brown Gryffindor 1979
Lisa Turpin Ravenclaw 1979
Luna Lovegood Ravenclaw 1981
Mandy Brocklehurst Ravenclaw 1979
Marcus Flint Slytherin 1975
Marietta Edgecombe Ravenclaw 1978
Michael Corner Ravenclaw 1979
Millicent Bulstrode Slytherin 1979
Neville Longbottom Gryffindor 1980
Padma Patil Ravenclaw 1979
Pansy Parkinson Slytherin 1979
Parvati Patil Gryffindor 1979
Penelope Clearwater Ravenclaw 1976
Robert Hilliard Ravenclaw 1974
Roger Davies Ravenclaw 1978
Romilda Vane Gryffindor 1981
Ronald Bilius Weasley Gryffindor 1980
Seamus Finnigan Gryffindor 1979
Susan Bones Hufflepuff 1979
Terence Higgs Slytherin 1979
Terry Boot Ravenclaw 1980
Tracey Davis Slytherin 1980
Vincent Crabbe Slytherin 1979
from cs50 import SQL
from csv import reader
from sys import argv
db = SQL("sqlite:///students.db")
if len(argv) < 2:
print("Usage error.use: import.py characters.csv")
exit()
with open(argv[1], newline='') as charactersFile:
characters = reader(charactersFile)
for character in characters:
if character[0] == 'name':
continue
# split the full name into first, last and middle name if present
fullName = character[0].split()
# insert the name and the other infos in the database, the database will show NULL if the student has no middle name
if len(fullName) < 3:
db.execute("INSERT INTO students(first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
fullName[0], None, fullName[1], character[1], character[2])
else:
db.execute("INSERT INTO students(first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
fullName[0], fullName[1], fullName[2], character[1], character[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment