mraps98

Python_storingAndReadingCSV

May 16th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. #pip install pretty table
  2. import csv
  3. from prettytable import from_csv
  4.  
  5. def printDb():
  6.     with open('db.csv','r', newline='') as fo:
  7.         with open('db.csv','r') as fo
  8.         x = from_csv(fo)
  9.         print(x)
  10.         #uncomment the below if you don't have prettytable and comment the previous 3 lines
  11.         # reader = csv.reader(fo)
  12.         # next(reader)
  13.         # print("FirstName\tLastname\tAge\tNationality")
  14.         # for line in reader:
  15.         #     print(line[0] + "\t\t" + line[1] + "\t\t" + line[2] + "\t" + line[3])
  16.        
  17. def addToDb(fname,lname,age,nationality):
  18.     with open('db.csv', 'a', newline='') as fo:
  19.         writer = csv.writer(fo)
  20.         writer.writerow([fname,lname,age,nationality])
  21.  
  22. def displayMenu():
  23.     choice = input("1. Display Current Database\n2. Add New Person to Database")
  24.     while int(choice) < 1 or int(choice) > 2:
  25.         choice = input("Please choose either 1 or 2")
  26.     if int(choice) == 1:
  27.         printDb()
  28.     elif int(choice) == 2:
  29.         takeInput()
  30.    
  31. def takeInput():
  32.     fname = input("Enter First Name: ")
  33.     lname = input("Enter Last Name: ")
  34.     age = input("Enter Age: ")
  35.     nationality = input("Enter Nationality: ")
  36.     addToDb(fname,lname,age,nationality)
  37.  
  38. while True:
  39.     displayMenu()
  40.    
  41.     retry = input("Press N to quit or any key to go back to homescreen: ").upper()
  42.     if retry == "N":
  43.         break
Advertisement
Add Comment
Please, Sign In to add comment