Advertisement
Guest User

Untitled

a guest
Oct 14th, 2020
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #IMPORT.PY
  2. from cs50 import SQL
  3. import sys, csv
  4.  
  5. db = SQL("sqlite:///students.db")
  6.  
  7. def main():
  8. check()
  9. load()
  10.  
  11.  
  12. def check():
  13. if len(sys.argv) != 2:
  14. print("Usage: python import.py <file.csv>")
  15.  
  16.  
  17. def load():
  18. with open(sys.argv[1], 'r') as csvfile:
  19. csv_dict = csv.DictReader(csvfile)
  20. for line in csv_dict:
  21. insert(line["name"], line["house"], line["birth"])
  22.  
  23. def insert(name, house, birth):
  24. spaces_count = name.count(' ')
  25. split = name.split(' ')
  26. first = split[0]
  27. if spaces_count == 2:
  28. middle = split[1]
  29. last = split[2]
  30. else:
  31. last = split[1]
  32. db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", (first, middle, last, house, birth))
  33.  
  34.  
  35. main()
  36.  
  37.  
  38.  
  39. #ROSTER.PY
  40.  
  41. from cs50 import SQL
  42. import csv, sys
  43.  
  44. db = SQL("sqlite:///students.db")
  45.  
  46. def main():
  47. if len(sys.argv) != 2:
  48. print("Usage: python roster.py <house>")
  49. house = sys.argv[1].lower().capitalize()
  50. grab(house)
  51.  
  52.  
  53. def grab(house):
  54. #you can ORDER BY with more than 1 ORDER as shown:
  55. table = db.execute("SELECT * FROM students WHERE house = (?) ORDER BY last ASC, first ASC", house)
  56. for row in table:
  57. print(row["first"], end=' ')
  58. if row["middle"] != None:
  59. print(row["middle"], end=' ')
  60. print(row["last"], end=', ')
  61. print("born", end=' ')
  62. print(row["birth"])
  63.  
  64. main()
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement