Advertisement
Guest User

houses/import.py

a guest
Apr 27th, 2020
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. from sys import argv, exit
  2. import csv
  3. from cs50 import SQL
  4.  
  5.  
  6. def main():
  7.     # check usage
  8.     if len(argv) != 2:
  9.         print("Usage: python import.py filename.csv")
  10.         exit(1)
  11.  
  12.     file = open(argv[1], "r")
  13.     csv_data = get_data(file)
  14.  
  15.     # get all data from csv sorted in lists
  16.     firsts, middles, lasts = get_names(csv_data)
  17.     houses = get_field(csv_data, 'house')
  18.     births = get_field(csv_data, 'birth')
  19.  
  20.     # assuming all lists have the same lenght
  21.     for i in range(len(firsts)):
  22.         db = SQL.execute("INSET INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", firsts[i], middles[i], lasts[i], houses[i], int(births[i]))
  23.  
  24.     file.close()
  25.  
  26.  
  27. # returns three lists with first, middle and last names
  28. def get_names(data):
  29.     firsts = []
  30.     middles = []
  31.     lasts = []
  32.  
  33.     for person in data:
  34.         name = person['name'].split()
  35.  
  36.         firsts.append(name[0])
  37.         if len(name) == 3:
  38.             middles.append(name[1])
  39.             lasts.append(name[2])
  40.         # if a person doesn't have a middle name, then middle field is None
  41.         elif len(name) == 2:
  42.             middles.append(None)
  43.             lasts.append(name[1])
  44.  
  45.     return firsts, middles, lasts
  46.  
  47.  
  48. # returns a list with the values of a key 'field'
  49. def get_field(data, field):
  50.     list = []
  51.  
  52.     for person in data:
  53.         list.append(person[field])
  54.  
  55.     return list
  56.  
  57.  
  58. # read csv in a list of dictioaries
  59. def get_data(file):
  60.     reader = csv.DictReader(file)
  61.     data = []
  62.  
  63.     for row in reader:
  64.         data.append(dict(row))
  65.  
  66.     return data
  67.  
  68.  
  69. if __name__ == "__main__":
  70.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement