Importing data from csv to database using Python

I need to create a database using info from a csv file, format:
name,house,birth example:

Adelaide Murton,Slytherin,1982   Adrian Pucey,Slytherin,1977 

Then I need to export to the database after splitting the name in the following format: first | middle | last | house | birth

Below is my code; it exports like 1st row only first name, 2nd row only middle name, 3d row only last name, 4th row only house , etc. and everything else appears NULL. I end up having 792 rows instead of 40 in my database. Output image

import csv import sys import cs50  db = cs50.SQL("sqlite:///students.db")  if len(sys.argv) != 2:         sys.exit("Usage: import.py file.csv")      with open(sys.argv[1],'r') as f:     reader = csv.DictReader(f)     for row in reader:         x = row["name"].split()         db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?,?,?,?,?)", x[0], x[1] if len(x)==3 else None, x[2] if len(x)==3 else x[1], row["house"], row["birth"]) 
Add Comment
1 Answer(s)

Make sure the students table is empty before running import, otherwise all the rows from all the attempts, buggy or not, are in the database. A bug that creates the described output would only insert approx 280 rows. (7 db rows per 1 csv row)

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.