Advertisement
JAS_Software

CSV test

May 7th, 2021
74
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import csv
  2.  
  3. def getFileRecords(filename):
  4.     with open(filename) as file:
  5.         #read file and store data to an object called records
  6.         #data is stored to an object so that it can be iterated over
  7.         #records = csv.reader(file,delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
  8.         records = csv.reader(file,delimiter=',')
  9.         for record in records:
  10.             print(record[0],record[1])
  11.  
  12. def addRecord(filename,name,food):
  13.     #append a record to the file
  14.     with open(filename,'a') as file:
  15.         #overwrite the line terminator to avoid blank line being added after new record
  16.         #https://stackoverflow.com/questions/34289402/python-csv-writer-leaving-blank-rows/34291877
  17.         records = csv.writer(file,delimiter=',',lineterminator='\n')
  18.         records.writerow([name,food])
  19.  
  20. def getName():
  21.     response = input('Enter a name: ').strip()
  22.     if response == '':
  23.         response = ''
  24.     return response
  25.  
  26. def getFood(name):
  27.     response = input('Enter a food for {}: '.format(name)).strip()
  28.     if response == '':
  29.         response = ''
  30.     return response
  31.  
  32. def collectFoods(filename):
  33.     #ask for name and food until name is blank
  34.     ask = True
  35.     while ask:
  36.         name = getName()
  37.         if name == '':
  38.             ask = False
  39.         else:
  40.             food = getFood(name)
  41.             addRecord(filename,name,food)
  42.  
  43. filename = 'foods.csv'
  44. collectFoods(filename)
  45. getFileRecords(filename)
  46.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement